問題是,爲什麼只有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
在這種情況下,請重新說明問題,以便清楚。 –