在模板类中,如何使用其他类型名称定义函数
In a templated class, how do I define a function with a different typename
编辑:这是不是标准模板问题的重复。
我的场景涉及一个模板的类和该类的成员函数,这些参数是模板的,但与类别相同的类型。
即使我将定义放在标题中,我仍然找不到正确的语法。
有人可以帮助我解决我的具体问题吗?
我的简化代码:
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>&);
相关文章:
- 我可以使用 decltype() 或其他东西通过指针获取真实类型吗?
- 为什么 c++ 中的 main() 函数不采用除 int 和 void 之外的任何其他返回类型
- 泛型枚举和其他类型的重载模板函数
- 为什么重载运算符可以返回其返回类型以外的其他内容?
- 在其他容器中使用 boost::container::static_vector 时,GCC 编译错误"将'const s'绑定到类型's&'的引用丢弃限定符"
- 将结构时间规范添加到类(似乎没有其他类型的)会导致EXEC_BAD_ACCESS
- 哪些 C++ 数据类型是 Metal 和所有其他 C++ 平台共有的
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 严格的别名是否会阻止您通过其他类型写入 char 数组?
- 使用字节向量作为其他类型的原始存储是一种好的做法吗
- 只知道运行时的数据类型.如何将数据详细信息隐藏到使用它们的其他类
- C++ 在方程中使用变量;错误:表达式必须具有整数或无作用域枚举类型及其他
- 没有模板变量的模板化类型和其他使用此类的模板化类型
- 从其他类声明类类型变量会给出 C2143 错误(在"*"之前缺少";")
- 针对特殊情况,使用其他状态信息扩展基元类型
- 区分键盘记录器中的密码和其他类型的键盘输入
- C++模板专用化 - 将其他整数类型委托给uint64_t
- 如果类包含基类类型的成员作为第一个元素,后跟其他成员,编译器是否可以优化空基?
- 对于其他类型的void_t,是否有标准的概括
- 如何将模运算符与其他数据类型一起使用