【问题标题】:VC++ Template Compiler Error C2244: Unable to Match Function Definition to an Existing DeclarationVC++ 模板编译器错误 C2244:无法将函数定义与现有声明匹配
【发布时间】:2011-06-25 03:15:11
【问题描述】:

我在使用 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 的返回类型“不同”?这是一个错误吗?

我还应该提到,如果函数被声明为内联,错误就会消失。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 这是否也解释了为什么在类中实现内联方法不会出现错误?我原以为它在哪里实施不会有什么不同。
    • 是的。您可以在 C++ 中重载名称,但前提是重载发生在不同的范围内。
    • 另外,尽管 i 在技术上可能不同,但它们的值是相同的。由于 i 是一个非类型模板参数,为什么它的身份比它的值更重要?
    • 好吧,它们的值是否相等并不重要(从编译器的角度来看,它甚至没有意识到这一点)。如果你写“int i = 1; int i = 1;”,它仍然是一个错误。例如在函数体中。
    猜你喜欢
    • 2012-11-06
    • 2013-01-10
    • 2021-11-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2018-09-06
    相关资源
    最近更新 更多