c++ - constexpr 和 inline 函数可以重新定义吗?

标签 c++ function inline 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() 将调用 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 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 函数是隐式的 inline,它具有 inline 函数的所有属性。因此,constexpr 函数可以有多个定义,前提是每个定义出现在不同的翻译单元中

为什么你的程序失败了:

在您的情况下,程序失败是因为您违反了这条规则。也就是说,您在同一翻译单元(即 main.cpp)中重新定义相同的 constexpr 函数。

关于c++ - constexpr 和 inline 函数可以重新定义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24716801/

相关文章:

javascript - 为什么我的 "Rock Paper Scissors"程序无法运行并且不断使我的页面崩溃?

c - 不使用库函数的 Ascii 到整数

generics - F# 泛型类型约束和鸭子类型

python - 使用 BeautifulSoup 删除所有内联样式

c++ - 如何在编译时检查内联函数的参数是否已知?

c++ 项目构建成功但给出 g++ 编译器错误消息

c++ - C++11如何判断一个类是否指定了嵌套类定义或typedef?

C++:函数重载和声明顺序的困惑

c++ - Spirit X3 编译错误 "a template declaration cannot appear at block scope"

c++ - pthread sleep() 函数停止整个执行