【问题标题】:Strange compile error when calling explicitly specialized class member template function调用显式专用类成员模板函数时出现奇怪的编译错误
【发布时间】:2016-09-09 07:52:36
【问题描述】:

使用 GCC 5.1.0 (tdm64-1) 编译以下代码时出现奇怪的编译错误

template <class T>
struct test {
    template <class X>
    bool func();
};

template <class X, class Y>
bool testfunc(X x, Y y)
{
  test<Y>  s;

  if (s.func<X>())    // <-- parse error here
      return false;
}

void func2()
{
 testfunc( double(), long() );
}

错误是

testX.cpp: In function 'bool testfunc(X, Y)': 
testX.cpp:12:15: error: expected primary-expression before '>' token 
   if (s.func<X>()) 
               ^ 
testX.cpp:12:17: error: expected primary-expression before ')' token 
   if (s.func<X>()) 

请注意,该错误仅出现在 Y 为模板参数的版本中。当我删除 Y 模板参数并使用已知类型(例如 test)实例化测试时,它编译没有错误。

那么这里出了什么问题?

【问题讨论】:

    标签: c++ templates compiler-errors


    【解决方案1】:

    改变这个:

    if (s.func<X>()) 
    

    到这里:

    if (s.template func<X>())
    

    原因是s.func&lt;X&gt; 是一个依赖名称,因此编译器无法判断func 是一个模板成员函数。

    【讨论】:

      【解决方案2】:

      由于s.func&lt;X&gt;()是一个依赖名,你需要告诉编译器func是一个模板,使用template关键字:

      s.template func<X>()
      

      【讨论】:

      • 太棒了。但是歧义在哪里? template 关键字是只指定 func 是一个模板,还是它是一个模板成员函数?即使我告诉编译器它是一个模板,编译器仍然不知道它是一个成员还是一个函数。 (也许这从语法上很清楚)
      • @AndreasH。您不能有模板成员变量,因此从语法中可以清楚地看出。问题在于 &lt;&gt; 标记,它们在 C++ 中严重过载。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-25
      • 2019-08-31
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 2019-02-17
      • 1970-01-01
      相关资源
      最近更新 更多