explicit instantiation of a function template having integers as template parameters

140 views Asked by At

I am trying to explicitly instantiate a function template. Please see the code snippet

main.cpp:

void func(int * );

int main()
{
    int m = 3, n = 5;

    int *ptr;

    ptr = &m;

    func(ptr); //function call

    <do-Something>
    .....
    .....

}

The func() function is in this cpp file

func.cpp :

#include "class_def.h"

template <int x1, int x2, int x3>
void sum(int *, myclass<x1, x2, x3> &); //template declaration

void func(int *in)
{
    myclass<1,2,3> var;
    sum(in,var);  //call to function template
    <do-Something>
    .....
    .....

}

class_def.h :

template<int y1, int y2, int y3>
class myclass
{
public:
    int k1, k2, k3;
    myclass()
    {
        k1 = y1;
        k2 = y2;
        k3 = y3;
    }
};

The definition of the function template "sum" resides in another hpp file

define.hpp :

#include "class_def.h"

template <int x1, int x2, int x3>
void sum(int *m, myclass<x1, x2, x3> & n)  //function template definition
{
    <do-Something>
    .....
    .....
}

Now, for instantiating this template i wrote the following code statement below the definition.

template void sum<int, int, int>(int *, myclass<1, 2, 3> &);

But still am getting the linkage error as

undefined reference to void sum<1, 2, 3>(int*, myclass<1, 2, 3>&)

What am i doing wrong here?

1

There are 1 answers

2
eerorika On BEST ANSWER

You say that define.hpp is not included in any compilation unit. Well, that's your problem. Because now neither the definition of the template nor the explicit instantiation exist in any compilation unit and therefore will never be compiled.

Changing the file from a header to a source-file and adding that to the compilation should fix it.

Besides that, there is the syntax error in the instantiation. It should be template void sum<1, 2, 3>(int *, myclass<1, 2, 3> &); as pointed out by Jarod42.