Unlinke other functions,inline and constexpr functions may be defined multiple times in the program.
我使用下面的一个constexpr cfunc()的两个定义,期待foo_0()将调用第一个def,而foo_1()将调用第二个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; }
解决方法
按照标准说明:
从§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函数是隐含内联的,它具有内联函数的所有属性.因此,如果每个定义都出现在不同的翻译单元中,则constexpr函数可以有多个定义.
为什么你的程序失败:
在你的情况下,程序失败,因为你违反了这个规则.也就是说,您在同一个翻译单元(即main.cpp)中重新定义相同的constexpr函数.
原文地址:https://www.jb51.cc/c/112033.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。