Explicit instantiation of member function template of class template

戏子无情 提交于 2019-12-23 18:34:10

问题


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.

来源:https://stackoverflow.com/questions/45596922/explicit-instantiation-of-member-function-template-of-class-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!