VC++模板编译器错误C2244:无法将函数定义与现有声明匹配

VC++ Template Compiler Error C2244: Unable to Match Function Definition to an Existing Declaration

本文关键字:定义 函数 声明 编译器 错误 C2244 VC++      更新时间:2023-10-16

我在使用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)'

如果删除了结构Bi的声明,编译器错误就会消失。我认为这是因为F的返回类型的模板参数绑定到B中的静态成员i,而不是B的模板参数。当i的值相同时,为什么F的返回类型"不同"?这是个虫子吗?

我还应该提到,如果函数是内联声明的,那么错误就会消失。

问题是在同一范围内两次声明相同的名称。如果您重命名静态常量int i或模板参数,它应该可以工作。