问题是,为什么只有M::operator<<
的调用会导致链接错误,而不是在应该调用std::cout::operator<<
?为什么M :: operator <<导致链接错误,而不是std :: cout :: operator <<
的代码如下:
#include <iostream>
struct M {
inline M() {}
template <typename T>
inline M& operator <<(const T& val) {
std::cout << "ref." << val;
return *this;
}
template <typename T>
inline M& operator <<(T* const& pointer) { // NOLINT
std::cout << "ptr." << pointer;
return *this;
}
};
class PJTest
{
public:
~PJTest()
{
M()
<< "Failed to remove file '" << fname << "' because: stuff\n"; // 25
std::cout
<< "Failed to remove file '" << fname << "' because: stuff\n"; // 28
}
protected:
static auto constexpr fname = "what's in a name?";
};
int main() {
PJTest pt;
}
与g++ -g -O0 -std=c++11 -Wall -pedantic -Wextra wtf.cc
结果编译在
wtf_test.cc:25: undefined reference to `PJTest::fname'
注意没有错误的线28时,它应该!
g++ -g -O2 -std=c++11 -Wall -pedantic -Wextra wtf.cc
成功。 (克++ 4.8.4从Ubuntu的14.04LTS)和行为与G ++ 5.3.0
与铛编译相同++总是无论失败优化级别的,但同样,只对线25;我知道我可以通过添加constexpr const char* PJTest::fname;
来解决这个问题,但我想了解为什么它在clang ++中导致错误。
[Undefined reference to static constexpr char \ [\]]可能的重复(http://stackoverflow.com/questions/8016780/undefined-reference-to-static-constexpr-char) –
我知道修补程序是添加'constexpr const char * PJTest :: fname;',问题是为什么只有对'M :: operator <<'的调用会导致错误,而不是对'std :: cout :: operator <<'的调用。 – Bulletmagnet
在这种情况下,请重新说明问题,以便清楚。 –