"Implicit instantiation of undefined template" when forward declaring template class

I've got some code in which I need to forward-declare the a template class (or at least, forward-declaring would make things a lot easier for me...). I've written a simplified version of the problem I'm having so I can display it here:

template<bool>
class MyTemplateClass;

int main( int argc, char* argv[] )
{
    MyTemplateClass<false> myTemp;  // error here
    myTemp.GetTheValue();
    return 0;
}

template<bool bShouldMult>
class MyTemplateClass
{
    int m_myint;
    float m_myfloat;

public:
    MyTemplateClass() : m_myint(5), m_myfloat(3.0f) {}
    float GetTheValue()
    {
        return m_myint * (bShouldMult ? m_myfloat : 1.0f);
    }   

};

The error I'm getting at the commented line is:

Error - implicit instantiation of undefined template 'MyTemplateClass<false>'

What other detail do I need to include in a forward declaration of MyTemplateClass? Since the error isn't coming from the next line down I'm assuming it isn't due to the fact that the method is undefined. The compiler I'm using is LLVM/CLang, and I'm compiling on Mac.


Did you forget to #include something?

I got this after forgetting to

#include <array>

When using a std::array

:^)


In order to declare a variable of any type, template or not, the entire definition of that type must be available. You cannot forward-declare a template, and then start using it as if it were defined. All you can do at that point is declaring a pointer to an object of a type based on the template, like this:

MyTemplateClass<false> *myTempPtr;  // No error here

Unfortunately (but not unexpectedly) this moves the error to the next line. The problem of initializing that pointer remains: once you attempt to invoke new MyTemplateClass<false>, you will see an error.

You need to re-arrange your code to move the definition of the template ahead of its place of use. This may be somewhat tedious, but there is no way around it: the compiler needs to have the entire definition at the point where you start instantiating your template and calling its methods.


It is from my understanding that you can not forward declare something and then instantiate it in your stack (template or not).

Also I don't think there's a very wide support for forward definition of template class