我在使用Visual Studio 2010时遇到了编译错误,我已将其简化为以下代码:
template <int i> struct A
{
typedef int T;
};
template<int i>
struct B
{
static const int i = i; // <-- this seems to cause the problem
typename A<i>::T F();
};
template<int i>
typename A<i>::T B<i>::F() { return B<i>::i; }
此代码产生此错误:
repro.cpp(15): error C2244: 'B<i>::F' : unable to match function definition to an existing declaration
repro.cpp(12) : see declaration of 'B<i>::F'
definition
'A<i>::T B<i>::F(void)'
existing declarations
'A<i>::T B<i>::F(void)'
如果删除了struct i
中B
的声明,编译器错误就会消失。我相信这是因为返回类型F
的模板参数绑定到i
中的静态成员B
而不是B
的模板参数。当F
的值相同时,为什么i
'的返回类型会有所不同?这是一个错误吗?
我还应该提一下,如果函数是内联声明的,那么错误就会消失。
答案 0 :(得分:1)
问题是您在同一范围内两次声明相同的名称。如果重命名静态const int i或模板参数,它应该可以工作。