c++ - 显式运算符 bool 的显式模板实例化

标签 c++ template-specialization explicit-conversion

我试图理解为什么会出现链接器错误

( 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;

最佳答案

显式模板实例化必须使模板定义可见。

所以你必须把

template Foo<int>::operator bool() const;

在 Foo.cpp 中,而不是 main.cpp 中。

Demo

关于c++ - 显式运算符 bool 的显式模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70848803/

相关文章:

c++ - 具有非专用模板参数的虚拟方法

c++ - 我不能将大小为 8 字节的类类型转换为 uint64_t 吗?

c++ - 在类外定义显式运算符 bool() 时出错

c++ - 转换迭代器和 const_iterators

c++ - 将文件中的多个输入分隔为偶数或奇数

c++ - 64位MFC版本访问冲突异常

c++ - enable_if 用于类模板特化,参数不是 void

C++ 如何基于部分特化创建 std::tuple 类型?

c++ - 为什么这个 shared_ptr 在超出范围时抛出断言?

c++ - 包含互斥 C++ 时的套接字问题