微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 可以重新定义constexpr和内联函数吗?

我正在核实C Primer的声明:

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;

}

解决方法

是的,与其他函数不同,在程序中可以定义多个内联和constexpr函数.但是,定义必须完全匹配.

按照标准说明:

从§7.1.5 / 2 constexpr指定器[dcl.constexpr]:

constexpr functions and constexpr constructors are implicitly inline.

从§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 举报,一经查实,本站将立刻删除。

相关推荐