c++ - 为什么这个显式模板特化不起作用?

标签 c++ templates

来自这段代码:

// Example program
#include <iostream>
#include <string>

struct Z { static const int z = 1; };
struct Y { static const int y = 2; };

template <typename A> struct TE { int foo(); int bar(); };

template <> int TE<Y>::bar() { return foo(); }
template <typename A> int TE<A>::bar() { return foo(); }

template <> int TE<Y>::foo() { return Y::y; }
template <typename A> int TE<A>::foo() { return A::z; }

template struct TE<Z>;
template struct TE<Y>;

int main()
{
    TE<Z> z;
    TE<Y> y;

    std::cout << z.bar() << std::endl;
    std::cout << y.bar() << std::endl;
    return 0;
}

有这个错误

21:28: error: specialization of 'int TE<A>::foo() [with A = Y]' after instantiation
 In instantiation of 'int TE<A>::foo() [with A = Y]':
13:12:   required from here
28:15: error: 'z' is not a member of 'Y'
 In member function 'int TE<A>::foo() [with A = Y]':
29:1: warning: control reaches end of non-void function [-Wreturn-type]

这些实现是在单独的 cpp 文件中完成的。并且结构在 header 中,典型的显式模板实例化。

为什么会这样

int TE<Y>::bar() { return foo(); }

尝试使用它

template <typename A> int TE<A>::foo() { return A::z; }

而不是这个

template <> int TE<Y>::foo() { return Y::y; }

最佳答案

http://en.cppreference.com/w/cpp/language/template_specialization

显式特化只能出现在与主模板相同的命名空间中,并且必须出现在非特化模板声明之后

此外,您还需要遵循单一定义规则 (ODR)。所以通常您会在同一个标​​头中提供您的实现。

关于c++ - 为什么这个显式模板特化不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36597490/

相关文章:

c++ - 使用CreateWindow显示BMP

c++ - 一个类的属性仅由外部环境使用是否可以接受?

asp.net - 使用 itext (itextsharp) 替换一个 PDF 模板页面上的多个不同图像

c++ - 冲突声明/重新定义 : different basic types

c++ - 一种将 C++ 代码划分为 .h 和 .cpp 文件对程序员透明的工具

c++ - 在实时 Fedora 上编译 C++ 程序的命令

c++ - mycomparison 是对象、函数还是函数指针?

c++ - C++ 模板可以检查给定类型的函数是否已重载吗?

不使用 atoi() 或 stoi() 的 C++ 字符串到 int

c++ - std::array 的部分模板参数推导或解决方法?