内联模板专业化 [英] Inlining Template Specialization

查看:102
本文介绍了内联模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的头文件foo.h包含在我的整个项目中,那么当它包含的所有内容都是:

If I have a header foo.h which I include all over my project, it seems to work fine when all it contains is:

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

但是当我在foo.h中添加规范化时,会出现一个定义规则(ODR)错误:

But I get one definition rule (ODR) errors when I add a specalization to foo.h:

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

很明显,我可以通过inline'专业化来解决此问题.我的问题是,为什么我需要这样做?如果模板没有违反ODR,为什么要进行专业化处理?

Obviously I can solve this by inline'ing the specialization. My question is, why do I need to? If the template doesn't violate ODR, why does a specialization?

推荐答案

显式专业化不是隐式内联的.必须将其显式内联.

An explicit specialization is not implicitly inline. It must be explicitly made inline.

[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

-示例]

所以您必须这样做,因为标准规定您必须这样做.

So you have to do it, because the standard says you have to do it.

这篇关于内联模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆