【发布时间】:2017-10-13 03:24:23
【问题描述】:
我有一个配置类
// config.hpp
class Config {
public:
static constexpr int a = 1;
static constexpr int b = 1;
}
并包含在 main.cpp 中
// main.cpp
#include "config.hpp"
int main () {
std::cout << Config::a << std::endl; // this is ok
std::shared_ptr<otherClass> stream = std::make_shared<otherClass>(
Config::a); // compile error
}
编译器说undefined reference to Config::a
它在使用cout 时有效,但在shared_ptr 构造函数中无效。
我不知道为什么会这样。
【问题讨论】:
-
你需要像c++17之前的静态成员一样在命名空间范围内定义
a,即constexpr int Config::a; -
为什么
cout有效? -
这是完美转发和 odr 使用的不幸结果,导致
make_shared不起作用。make_shared<otherClass>(int(Config::a))也可以使用 -
好的。希望你详细解释一下。谢谢!
标签: c++ c++17 definition constexpr one-definition-rule