0

I'm learning templates and I noticed that I cannot seem to declare and define a template separately. With a function, I'd declare it before main and define it after main to keep good readability. But it seems like I have to write the whole template at once, and before main. But I want my main function to be at the top. Surely there would be a way to do this but I couldn't find it.

'''

#include <iostream>

using std::cout;
using std::endl;

template <typename T>
void Print(T a);

int main(void)
{
    Print("Hey");
    // free variables
    return 0;
}

void Print(T a)
{
    cout << a << endl;
}

'''

RubyShanks
  • 138
  • 8
  • 3
    You can separate the definition and declaration, but both pieces must be seen by the compiler before any use of the template. Explicit instantiation of a template is an exception to this rule, but it's not a generally useful technique. – john Jan 07 '23 at 07:25
  • 1
    The better solution is to put all your template code in one header file. And include that in your main.cpp file. That way you don't even have to split implementation from declaration. – Pepijn Kramer Jan 07 '23 at 08:49

0 Answers0