0

For example, i have such code:

.h-file:

template <typename T1>
class Templ
{
    public:
    template <typename T>
    T foo (T t);
};

.cpp-file:

template <typename T1>
template <typename T>
T Templ<T1>::foo (T t)
{
    qDebug() << "Non-specialised template";
    return t;
}

template <>
template <>
int Templ<void>::foo (int t)
{
    qDebug() << "Specialised class template void> & method template <int>";
    return t;
}

if I call something like that:

Templ <void>t;
int i = t.foo<int>(1);

I will get expected "Specialised class template void> & method template " message, but if i want to call unspecialized function like that:

Templ <float>t;
int i = t.foo<bool>(1);

I will get undefied reference linker error. How do I call unspecialized function?

Also, how do I define specialized function of unspecialized class? I want to do something like

template <typename T1>
template <>
int Templ<T1>::foo (int t)
{
    qDebug() << "Specialised class template void> & method template <int>";
    return t;
}

but, obviosly, it will not compile.

DmitryU
  • 31
  • 4
  • 4
    Related: [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – πάντα ῥεῖ Jan 14 '16 at 15:29
  • 1
    Your unspecialized version [works](http://coliru.stacked-crooked.com/a/511b362d6d16780a) if you define the functions in the header. – TartanLlama Jan 14 '16 at 15:36
  • TartanLlama, thx for advise, but in that case i ougth to declare function as inline, to preserve multiple definition. Also, i suppose it is not the best practice - to move realization to .h file. – DmitryU Jan 14 '16 at 20:48

0 Answers0