I have the following code:
#include<chrono>
#include<iostream>
using namespace std::chrono_literals;
#define MSG "hello"
#define DUR 1000ms
class mwe{
public:
static constexpr auto msg = MSG;
static constexpr auto dur_1 = DUR;
static constexpr std::chrono::milliseconds dur_2 = DUR;
static const std::chrono::milliseconds dur_3;
static constexpr decltype(DUR) dur_4 = DUR;
};
constexpr std::chrono::milliseconds mwe::dur_2;
const std::chrono::milliseconds mwe::dur_3 = DUR;
constexpr decltype(DUR) mwe::dur_4;
int main(void) {
std::cout << "str: " << mwe::msg << std::endl;
std::cout << "dur_1: " << mwe::dur_1.count() << std::endl;
std::cout << "dur_2: " << mwe::dur_2.count() << std::endl;
std::cout << "dur_3: " << mwe::dur_3.count() << std::endl;
std::cout << "dur_4: " << mwe::dur_4.count() << std::endl;
}
如果我通过以下方式编译它(使用g++ 4.9):
g++ -std=c++14 -O2 test.cpp
一切都按预期运行,但如果我通过编译
g++ -std=c++14 -O0 test.cpp
I get the following Error:
undefined reference to `mwe::dur_1'
我个人最喜欢dur_1的定义和声明方式,但如果没有启用优化,它在我的版本中无法与g++配合使用。 因为我所知道的所有其他方法(dur_2、dur_3、dur_4)都有它们的缺点(值冗余、没有自动类型推断,例如如果我将1000ms更改为1s等)。
你知道吗,如果这是gcc的一个bug,在生产模式下编译可以工作,但在没有优化的情况下不起作用吗?
还有没有其他可能的方法可以使其工作,而无需在类外定义dur_x的位置?
dur_1
没有被定义。不确定你的期望是什么。 - Lightness Races in Orbit