在模板类中,如何使用其他类型名称定义函数

In a templated class, how do I define a function with a different typename

本文关键字:类型 其他 函数 定义 何使用      更新时间:2023-10-16

编辑:这是不是标准模板问题的重复。

我的场景涉及一个模板的类和该类的成员函数,这些参数是模板的,但与类别相同的类型。

即使我将定义放在标题中,我仍然找不到正确的语法。

有人可以帮助我解决我的具体问题吗?


我的简化代码:

foo.h:

template<typename T1>
class Foo {
public:
    template<typename T2>
    static void bar(vector<T1>& a, vector<T2>& b);
};

foo.cpp:

#include <Foo.h>
template<typename T1>
template<typename T2>
void Foo<T1>::bar(vector<T1>& a, vector<T2>& b) {
    //code logic
}

goo.cpp:

#include <Foo.h>
int main(int argc, char** argv) {
    vector<int> a;
    vector<double> b;
    Foo<int>::bar(a, b);
}

我的错误:

undefined reference to
void Foo<int>::bar<double>(std::vector<int, std::allocator<int> >&, 
std::vector<double, std::allocator<double> >&)

我找不到定义模板的正确方法。

我还注意到打字机的顺序将更改错误(还将整个函数放在类声明中)。

什么是正确的语法?

您的问题不在声明或定义中。问题是定义和声明的分裂。那无法按照您的方式工作。编译foo.cpp时,您的模板没有可见的用途,因此不会创建实例。编译goo.cpp时,链接器将无法链接到它们。

这就是这个错误的含义:

未定义的引用对" void foo&lt> :: bar&lt; double>(std :: vector&lt; int,std :: plaster&lt; int&lt; int>>>>>>&amp;)'

如果您真的想做自己正在做的事情,则需要针对每种类型组合使用明确的实例化。

foo.cpp更改为此(请注意最后一行的显式实例定义):

template<typename T1>
template<typename T2>
void Foo<T1>::bar(std::vector<T1>& a, std::vector<T2>& b) {
    //code logic
}
template void Foo<int>::bar(std::vector<int>&, std::vector<double>&);
相关文章: