使用g ++和clang ++调用Integral模板成员函数时出错

时间:2015-08-30 19:42:12

标签: c++ templates gcc member clang++

我目前遇到了编译错误,我无法确定......

这是一个极小的工作示例:

#include <iostream>

template <typename T, int R>
class a_type
{
public:
     template <int N>
     double segment()
      {
           return 42;
      }
};

template <int M>
double func()
{
     a_type<double, M> a;
     return a.segment<1>();
}

int main(int argc, char *argv[])
{
     std::cout << func<10>() << std::endl;
     return 0;
}

GCC的错误消息为:

g++ main.cpp -o main
main.cpp: In function 'double func()':
main.cpp:18:26: error: expected primary-expression before ')' token
      return a.segment<1>();
                          ^
main.cpp: In instantiation of 'double func() [with int M = 10]':
main.cpp:23:28:   required from here
main.cpp:18:22: error: invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<'
      return a.segment<1>();
                  ^

Clang也说了类似的话:

clang++ main.cpp -o main
main.cpp:18:26: error: expected expression
     return a.segment<1>();
                         ^

因此,根据GCC的错误消息,&#39; a.segment&#39;是一个缺少括号的成员函数调用,显然会被拒绝。但这根本没有意义,因为我没有看到任何理由来对待这种表达。 此外,如果我将M改为第17行的任何整数,就像这样:

#include <iostream>

template <typename T, int R>
class a_type
{
public:
     template <int N>
     double segment()
      {
           return 42;
      }
};

template <int M>
double func()
{
     a_type<double, 58> a;
     return a.segment<1>();
}

int main(int argc, char *argv[])
{
     std::cout << func<10>() << std::endl;
     return 0;
}

然后代码编译并产生预期的结果。

如果有人能够启发并向我展示我在这里缺少的东西,我会非常高兴。

2 个答案:

答案 0 :(得分:4)

编译器不知道a.segment是模板(可能取决于M的值)。所以你必须告诉它:

return a.template segment<1>();

在你的第二个例子中,它知道a类型的所有内容,因此没有问题。

答案 1 :(得分:1)

编译器告诉你它有

的问题
 a_type<double, M> a;
 return a.segment<1>();

因为它无法分辨成员a可以拥有什么,因为它是一个模板(可能专门用于M的某些值。)

  

main.cpp:18:22: error: invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<' return a.segment<1>(); ^

如果segment是模板,则会将其视为segment<1>。如果segmenta的成员变量,则应将其编译为a.segment < 1。如何知道编译器?

您可以使用

解决此问题
return a.template segment<1>();
相关问题