【发布时间】:2016-07-09 08:23:02
【问题描述】:
当我尝试编译这个时,
#include <iostream>
struct K{
const static int a = 5;
};
int main(){
K k;
std::cout << std::min(k.a, 7);
}
我得到关注。 gcc 和 clang 都给出了类似的错误:
/tmp/x-54e820.o: In function `main':
x.cc:(.text+0xa): undefined reference to `K::a'
clang-3.7: error: linker command failed with exit code 1 (use -v to see invocation)
如果我遵循,它编译没有问题。这和std::min的写法有关系吗?
#include <iostream>
struct K{
const static int a = 5;
};
int main(){
K k;
std::cout << std::min((int) k.a, 7); // <= here is the change!!!
}
另一种避免错误的方法是我自己做min():
template <class T>
T min(T const a, T const b){
return a < b ? a : b;
}
类 C 预处理器 MIN 也可以正常工作。
【问题讨论】:
-
为什么要标记 gcc 和 clang?你应该只使用一种编译器,它看起来是铿锵声
-
ideone.com/yPtq6w 为我工作
-
尝试更改您的
min以通过引用获取参数。 -
你的例子应该有
#include <algorithm>对应std::min -
从 C++11 开始,另一种解决方法是使用 min:
std::min({k.a, 7})的列表形式。我认为这不是 odr-use 因为初始化列表按值复制。从 C++14 开始,列表形式甚至会产生constexpr。