3

What is the correct syntax for explicit instantiation of conversion operators?

I have the following header a.h

class A
{
public:
  template<typename T> operator T();
};

and the implementation a.cxx

#include "a.h"
template<typename T> A::operator T() {return 1;}
template A::operator int();

GCC 6.3 compiles as expected, but VC 14 (Visual Studio 2015) says:

error C2549: user-defined conversion cannot specify a return type

Is this an error in my code or a bug in VC? What would be the correct syntax vor VC?

YSC
  • 38,212
  • 9
  • 96
  • 149
Helmut Zeisel
  • 388
  • 1
  • 10
  • 2
    Setting aside the compilation error you'are asking about, which looks like a bug in VC, this code [is ultimately doomed to fail](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). – Sam Varshavchik Mar 09 '17 at 11:57
  • With GCC, the following main.cxx works as expected:#include "a.h" #include int main() { A a; auto b = static_cast(a); std::cout << b << std::endl; return 0; }. Without explicit instantiation it gives a link time error. – Helmut Zeisel Mar 09 '17 at 12:16
  • Now try it without explicit instantiation. The whole point of having templates is to have the compiler itself write the code for you. Being forced to explicitly instantiate ***every*** template instance defeats the purpose of having a template, somewhat. – Sam Varshavchik Mar 09 '17 at 12:37
  • This depends on the particular situation. In my case, as the author of A, I know for which Ts the conversions from A to T make sense. I could, of course, avoid templates, list all these Ts explicitely in the header and repeat the implementation in a.cxx. This, however, would be cumbersome and harder to maintain. – Helmut Zeisel Mar 09 '17 at 13:01

0 Answers0