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

时间:2011-06-25 03:15:12

标签: c++ visual-studio templates compiler-errors

我在使用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 iB的声明,编译器错误就会消失。我相信这是因为返回类型F的模板参数绑定到i中的静态成员B而不是B的模板参数。当F的值相同时,为什么i'的返回类型会有所不同?这是一个错误吗?

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

1 个答案:

答案 0 :(得分:1)

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