54

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.

3 Answers 3

151

Did you forget to #include something?

I got this after forgetting to

#include <array>

When using a std::array

:^)

3
  • 11
    For me it was #include <string> I was working on moving from gcc to clang. Jul 30, 2019 at 20:35
  • 1
    Yea there's some differences among compilers about default inclusion and nested inclusion of string and other libraries.
    – kmiklas
    Nov 12, 2020 at 16:34
  • 2
    For me, it was #include <vector> (note for beginners like me) Mar 12, 2021 at 4:59
40

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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.