C++17:在 .cpp 文件中定义静态 constexpr 成员函数

C++17: Defining static constexpr member functons in .cpp file

我在 .h 文件中声明了一个静态 constexpr 成员函数。如果我立即在 header 文件中定义函数,一切都会完美无缺。我一般倾向于在 .cpp 文件中定义函数(即使我希望它们内联,我也会使用 inline 关键字并再次这样做)所以当我尝试这样做时,一开始似乎没问题,但当我尝试时调用此函数时出现以下错误:

static constexpr uint16_t ClassA::myFoo()' used before its definition

我想知道是否有办法在 .cpp 文件而不是 header 中定义静态 constexpr 成员函数。如果那不可能或可能由于我使用的编译器而受到限制,那么在 .h 文件中定义函数是否有任何副作用? (我知道它对于普通函数是显式内联的,但我不确定对于 constexper 静态函数)。

PS:我正在使用 arm-none-eabi-g++ (c++17) 和 Clion 进行小型嵌入式项目。

I would like learn if there is a way to define a static constexpr member function in the .cpp file rather than the header.

是的...但是您必须在使用它的每个 TU 中定义该函数,因为它是一个内联函数。因此,将定义放入 header 中会更简单,这样相同的定义将包含在所有需要它的 TU 中。

它是一个内联函数,因为 constexpr 函数是隐式内联函数 - 即无论您是否使用 inline 关键字。

is there any side effects defining the function in the .h file ?

这样做的效果是函数定义将包含在每个包含 header 的 TU 中。在这种情况下,我不太明白你所说的 "side" 效果是什么意思。