c++ - 内联模板特化

标签 c++ inline template-specialization one-definition-rule template-function

如果我有一个 header foo.h,我将其包含在我的整个项目中,当它只包含以下内容时它似乎工作正常:

template<typename T>
void foo(const T param) {
    cout << param << endl;
}

但是当我向 foo.h 添加一个特化时,我得到一个定义规则 (ODR) 错误:

template<>
void foo(const bool param) {
    cout << param << endl;
}

显然,我可以通过内联特化来解决这个问题。我的问题是,为什么我需要这样做?如果模板不违反 ODR,为什么要专门化?

最佳答案

显式特化不是隐式内联的。它必须显式内​​联。

[temp.expl.spec]/12

An explicit specialization of a function or variable template is inline only if it is declared with the inline specifier or defined as deleted, and independently of whether its function or variable template is inline. [ Example:

template<class T> void f(T) { /* ... */ }
template<class T> inline T g(T) { /* ... */ }

template<> inline void f<>(int) { /* ... */ }   // OK: inline
template<> int g<>(int) { /* ... */ }           // OK: not inline

 — end example ]

所以你必须这样做,因为标准规定你必须这样做。

关于c++ - 内联模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51987423/

相关文章:

c++ - Xcode 5 在 usr/include 中找不到头文件

c++ - 全局非抛出::operator new 和 std::malloc 之间的区别

C++:初始化成员 Vector 值

JQuery 添加 css 不是内联的

c++ - 是否可以在C++标准库中实现always_false?

c++ - 是否可以获取正在监听 Windows 端口的进程的线程 ID?

c++ - 为什么非成员静态 constexpr 变量不隐式内联?

c# - winforms .Net 关于小方法的使用

C++ - 在具有非类型模板参数的模板化类上专门化函数模板

c++ - 在不使用继承或类特化的情况下禁用成员函数和变量