Tyson Hilmer
Tyson Hilmer

Reputation: 771

explicit template instantiation of explicit operator bool

I'm trying to understand why I get a linker error

( error LNK2001: unresolved external symbol "public: __cdecl Foo<int>::operator bool(void)const_ )

With the following code. If I move the definition of Foo::operator bool() to the header, it builds fine. Apparently there is a problem with the explicit template instantiation, but I'm not seeing it. Please help me understand why.

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;

Upvotes: 2

Views: 152

Answers (1)

Jarod42
Jarod42

Reputation: 217293

An explicit template instantiation must have the template definition visible.

So you have to put

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

in Foo.cpp, not main.cpp.

Demo

Upvotes: 3

Related Questions