考虑以下代码:
#include <vector>
struct A {
static constexpr int kDefaultValue = -1;
std::vector<int> v;
A(int n): v(n, A::kDefaultValue) {}
};
int main() {
A(10);
return 0;
}
无法链接(在OS X上,llvm clang、gcc 4.9都无法链接):
Undefined symbols for architecture x86_64:
"A::kDefaultValue", referenced from:
A::(int) in main.cpp.o
ld: symbol(s) not found for architecture x86_64
问题是什么?它可以通过将A::kDefaultValue
转换为int
来修复。或者通过将kDefaultValue
移出A
。这两种情况似乎都很丑陋。这是另一种制作链接的方式吗?
kDefaultValue
更改为static constexpr std::integral_constant<int, -1> kDefaultValue{};
。不需要外部定义,v(n, A::kDefaultValue)
将正常工作,并且适用于 C++11 及以后的版本。在线演示 - ildjarn