为什么我要重新定义‘template< class T>如果我在C ++中使用内联函数? [英] Why am I getting redefinition of ‘template<class T> if I use inline function in C++?

查看:313
本文介绍了为什么我要重新定义‘template< class T>如果我在C ++中使用内联函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个具有相同内容的头文件:

I have 2 header files that have identical content:

template<typename T> inline void func(){

}

我将这2个标头包含在main.cpp文件中,然后进行编译:

I include these 2 headers in a main.cpp file then I compile:

g++ main.cpp -o run

但是我得到了

In file included from main.cpp:2:0:
test2.cpp:1:34: error: redefinition of ‘template<class T> void func()’
 template<typename T> inline void func(){
                                  ^
In file included from main.cpp:1:0:
test.cpp:1:34: error: ‘template<class T> void func()’ previously declared here
 template<typename T> inline void func(){

如果使用可以重新定义的内联函数,我会收到什么错误消息?

What am I getting this error if use inline function which can be redefined?

推荐答案

您错过了一个关键环节.该标准在[basic.def.odr]/6中表示

You missing a key piece. The standard says in [basic.def.odr]/6 that

一个类类型(第9章),枚举类型(7.2),具有外部链接的内联函数(7.1.2),类模板(第14章),非静态函数模板(14.5)可以有多个定义. .6),类模板的静态数据成员(14.5.1.3),类模板的成员函数(14.5.1.1)或未在程序中指定某些模板参数的模板特殊化(14.7、14.5.5) 假设每个定义出现在不同的翻译单元中 [...]

强调我的

因此,可以对内联函数具有多个定义,但是这些定义必须位于单独的翻译单元(基本上是源文件)中.由于它们在同一个翻译单元中,因此违反了该规则,您会得到一个错误.

So, you're allowed to have have multiple definitions of the inline function, but those definitions need to be in separate translation units(basically source files). Since they are in the same translation unit, they are violating that and you get an error.

这篇关于为什么我要重新定义‘template&lt; class T&gt;如果我在C ++中使用内联函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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