Search code examples
c++templatesvisual-studio-2015c++14forward-declaration

Function Template Specialization with Forward Declared Type


Haven't been able to quite find a duplicate.

Is it possible to forward-declare the type used in a function specialization?

Consider the following code:

in .h

template <typename T>
T* Foo()
{
    //generic implementation
}

template<>
class SpecialT* Foo<class SpecialT>();

in .cpp

#include "SpecialT.h"

template<>
SpecialT* Foo<SpecialT>()
{
    //specialized implementation
}

Is there any syntax in which the above is possible and doesn't result in a slew of compiler errors (C2910, C2909, C2768, etc.)?

This of course compiles if "SpecialT.h" is included in the template header.


Solution

  • The simple workaround is to simply put the forward declaration on its own line:

    class SpecialT;
    template<>
    SpecialT* Foo<SpecialT>();
    

    VS 2015 on Godbolt accepts it just fine.