我正在验证 C++ Primer 上的声明:
Unlinke other functions, inline and constexpr functions may be defined multiple times in the program.
我在下面使用了两个 constexpr cfunc()
的定义,预计 foo_0()
将调用第一个 def 而 foo_1()
将调用 2nd def。然而,尝试因编译错误而失败(最后)。为什么?
constexpr int cfunc(){
return 42;
}
int foo_0(){
return cfunc();
}
constexpr int cfunc(){
return 42;
}
int foo_1(){
return cfunc();
}
int main(int argc, char **argv) {
cout << foo_0() << endl;
cout << foo_1() << endl;
/* testconstexprfunc2.cpp:24:15: error: redefinition of ‘constexpr int cfunc()’ */
/* testconstexprfunc2.cpp:16:15: error: ‘constexpr int cfunc()’ previously defined here */
return 0;
}
最佳答案
是的,与其他函数不同,inline 和 constexpr 函数可以在程序中定义多次。 但是,定义必须完全匹配。
根据标准的理由:
来自 § 7.1.5/2 constexpr 说明符 [dcl.constexpr]:
constexpr
functions andconstexpr
constructors are implicitlyinline
.
来自 § 3.2/6 一个定义规则 [basic.def.odr]:
There can be more than one definition of a class type (Clause 9), enumeration type (7.2),
inline
function with external linkage ... in a program provided that each definition appears in a different translation unit...
来自 § 7.1.2/4 函数说明符 [dcl.fct.spec]:
An
inline
function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case.
因此,由于 constexpr
函数是隐式的 inline
,它具有 inline
函数的所有属性。因此,constexpr
函数可以有多个定义,前提是每个定义出现在不同的翻译单元中。
为什么你的程序失败了:
在您的情况下,程序失败是因为您违反了这条规则。也就是说,您在同一翻译单元(即 main.cpp)中重新定义相同的 constexpr
函数。
关于c++ - constexpr 和 inline 函数可以重新定义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24716801/