我试图理解为什么会出现链接器错误
( error LNK2001: unresolved external symbol "public: __cdecl Foo<int>::operator bool(void)const_ )
使用以下代码。如果我将 Foo::operator bool() 的定义移到标题中,它就可以正常构建。显然,显式模板实例化存在问题,但我没有看到它。请帮我理解为什么。
Foo.hpp:
/* Foo.hpp */
template<class T>
struct Foo {
T x;
explicit operator bool() const;
};
Foo.cpp:
/* Foo.cpp */
#include "Foo.hpp"
template <class T>
Foo<T>::operator bool() const {
return true;
}
main.cpp:
/* main.cpp */
#include "Foo.hpp"
#include <iostream>
int main(int argc, char* argv[]) {
Foo<int> foo;
if (foo)
std::cout << "works" << std::endl;
}
template Foo<int>::operator bool() const;
最佳答案
关于c++ - 显式运算符 bool 的显式模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70848803/