具有整数作为模板参数的函数模板的显式实例化

时间:2015-06-08 06:49:42

标签: c++ templates explicit-instantiation

我正在尝试显式实例化一个函数模板。请参阅代码段

main.cpp中:

void func(int * );

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

    int *ptr;

    ptr = &m;

    func(ptr); //function call

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

}

func()函数位于此cpp文件中

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;
    }
};

函数模板“sum”的定义存在于另一个hpp文件中

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>
    .....
    .....
}

现在,为了实例化这个模板,我在定义下面编写了以下代码语句。

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

但仍然会出现链接错误

  

未定义引用void sum&lt; 1,2,3&gt;(int *,myclass&lt; 1,2,3&gt;&amp;)

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

您说define.hpp未包含在任何编译单元中。嗯,这是你的问题。因为现在任何编译单元都不存在模板的定义和显式实例化,因此永远不会编译。

将文件从标题更改为源文件并将其添加到编译中应修复它。

除此之外,实例化中存在语法错误。它应该是template void sum<1, 2, 3>(int *, myclass<1, 2, 3> &);,正如Jarod42所指出的那样。

相关问题