7

Supposing I have a class template in my header file with a member function template.

//file.hxx
template<class T>
struct A {
    T val;
    template<class U> foo(U a);
};

and I have in a .cpp the implementation of foo:

//file.cpp
#include "file.hxx"
#include <typeinfo>
template<class T> template<class U>
A<T>::foo<U>(U a){
    std::cout << "Type T: " << typeid(val).name() << std::endl;
    std::cout << "Type U: " << typeid(a).name() << std::endl;
}

If I want to explicitly instantiate my class and member function in the .cpp file for, say, int and float, I need something like:

template struct A<int>;
template struct A<float>;
template A<int>::foo<int>(int);
template A<int>::foo<float>(float);
template A<float>::foo<int>(int);
template A<float>::foo<float>(float);

which becomes a little verbose if I start having a lot of types of T and U. Is there any faster way to do this and still having the explicit instantiation of the templates in the cpp file? I was imagining something like

template<class T>
template A<T>::foo<int>(int);
template<class T>
template A<T>::foo<float>(float);
template struct A<int>;
template struct A<float>;

but it doesn't work.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Teloze
  • 279
  • 2
  • 8
  • 1
    if you can use boost, then try with `BOOST_PP_LIST_FOR_EACH`. You can also refer this link https://stackoverflow.com/questions/23946669/varadiac-macros-for-making-different-partial-specialization-of-a-class – Nipun Aug 09 '17 at 17:29
  • I really don't think you should worry too much about explicitly instantiating all the templates. In the bigger picture, they will most likely be dwarfed by the volume of other parts of your code base. – R Sahu Aug 09 '17 at 17:36
  • 1
    @R Sahu : I prefer explicit instantiation because 1) I like to keep the header clean from the actual implementation 2) I allow instantiation only for types I know the code is made for 3) reduce compiling time – Teloze Aug 09 '17 at 17:41
  • @Nipun: TY. I'll give a look to Boost even if I didn't want to have this dependence. – Teloze Aug 09 '17 at 17:43
  • 1
    @Teloze, I understand your motivation for explicit instantiation, and I am in favor of it. I am saying, don't worry too much about the explicit instantiations becoming too verbose or voluminous. Overall, they will be small part of your code base. – R Sahu Aug 09 '17 at 18:50
  • @R Sahu, I thought you were referring to the dimensions of the executable. My bad :P – Teloze Aug 09 '17 at 19:10

0 Answers0