这是我实际拥有的一些代码的最小测试用例.它在尝试评估时失败a.getResult<B>():
test.cpp: In function 'void printStuff(const A&)':
test.cpp:6: error: expected primary-expression before '>' token
test.cpp:6: error: expected primary-expression before ')' token
Run Code Online (Sandbox Code Playgroud)
代码是:
#include <iostream>
template< class A, class B>
void printStuff( const A& a)
{
size_t value = a.getResult<B>();
std::cout << value << std::endl;
}
struct Firstclass {
template< class X >
size_t getResult() const {
X someInstance;
return sizeof(someInstance);
}
};
int main(int, char**) {
Firstclass foo;
printStuff<Firstclass, short int>(foo);
printStuff<Firstclass, double>(foo);
std::cout << foo.getResult< double >() …Run Code Online (Sandbox Code Playgroud) 这个问题的答案在以下代码中说明:
#include <vector>
using std::vector;
struct foo {
template<typename U>
void vector();
};
int main() {
foo f;
f.vector<int>(); // ambiguous!
}
Run Code Online (Sandbox Code Playgroud)
main中的最后一行是不明确的,因为编译器不仅在vector内部查找foo,而且从内部开始作为非限定名称main.所以它找到了std::vector和foo::vector.要解决这个问题,你必须写
f.foo::vector<int>();
Run Code Online (Sandbox Code Playgroud)
我已经试过所有流行的C++编译器(这个程序g++,clang++,vc++和英特尔C++)和所有的编译器编译这个程序没有任何错误.那么,为什么他说这个程序有歧义呢?C++标准对此有何看法?