jeudi 21 janvier 2021

Explicit instantiation for a templated function: how should I compile? [duplicate]

when dealing with templated classes/functions, it's common practice to put both declarations and definitions inside the header.

However, for maintainability reasons, I do prefer to split declarations and definitions. I found here a way to do that (see accepted answer), but now I was trying to do that by means of explicit instantiation. Unfortunately, there's a thing that's not still clear to me and I can't find a proper answer, let me explain this two points with a minimal reproducible example:

Header foo.hpp where I write the declaration of the templated function foo

#ifndef foo_hpp
#define foo_hpp


template <typename T>
void foo();


#endif /* foo_hpp */

Then, foo.cpp file, where I define the function and use explicit instantiation

#include "foo.hpp"
#include <iostream>


template <typename T>
void foo(){
    std::cout << "Call to foo \n";
}

template void foo<int>(); //explicit istantiation

Now in the main.cpp file, the one I want to compile and then execute, I have

#include "foo.hpp"

int main(){
    
    foo<int>();
    return 0;
}

In order to compile (with -std=c++14 flag), I have to do

g++ -o main.x -std=c++14 main.cpp foo.cpp

The questions are:

  • is this the correct pattern to use explicit instantiation?
  • When I compile, do I have to compile both the .cpp files?

Of course, if I simply do:

g++ -o main.x -std=c++14 main.cpp 

ww have undefined symbols because the compiler doesn't have access to the implementation of the methods.

Aucun commentaire:

Enregistrer un commentaire