0

I have just learn a few pages about templates and have the following problem. A.h

struct A
{
   template<class T> T func();
}; 

A.cpp

template<class T>
T func()
{
   //do something
}

template<> int A::func<int>();
template<> char A::func<char>();

Now if I have this struct

template<class C>
struct B
{
    template<typename T>
    T func();
};

Will I have to write out all cases when func is to be used with what specific class C ?

e.g 
template<classX> int func<int>();
template<classX> char func<char>();
template<classY> int func<int>();
....
Hello Everyone
  • 329
  • 4
  • 11
  • Why are you enumerating all the possible uses *in either case*? That entirely negates the point of having template functions. – Silvio Mayolo Jan 17 '18 at 18:15
  • If the amount of specialisation is growing exponentially, then you are most likely trying to solve a problem (using templates) that requires a different solution. This feels like an XY-problem. What is the underlying issue that you want to solve with templates? – Richard Critten Jan 17 '18 at 18:15
  • If you move the implementations to the header file (or a file that is included in), no. – O'Neil Jan 17 '18 at 18:17
  • I leave it in `.cpp` for the sake of beauty. Now you enlighten me that it sux that way. Thanks. – Hello Everyone Jan 17 '18 at 18:20
  • 3
    Possible duplicate of [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Richard Critten Jan 17 '18 at 18:23
  • If you don't like having it in the *same* file as the declarations, what I usually do is put my template implementations in a `.tcc` file and include that at the bottom of the header. To the compiler, it's the same effect, but now to the developer it looks like it's in two separate files. – Silvio Mayolo Jan 17 '18 at 18:31
  • "I leave it in .cpp for the sake of beauty." What? If you split definition and declaration your optimizer has no chance to get all possible optimizations done, simply because the compiler don't see the complete picture. As a hammer on that problem you can switch on link time optimzer, ok. But it is less common to split definitions from declarations in C++ than in C! You should think again of "beauty" and see more the technical aspects! – Klaus Jan 17 '18 at 18:41

0 Answers0