当我在不同的目标文件中使用专用模板时,链接时出现"多重定义"错误.我找到的唯一解决方案涉及使用"内联"功能,但它似乎只是一些解决方法.如何在不使用"inline"关键字的情况下解决这个问题?如果那不可能,为什么?
这是示例代码:
paulo@aeris:~/teste/cpp/redef$ cat hello.h
#ifndef TEMPLATE_H
#define TEMPLATE_H
#include <iostream>
template <class T>
class Hello
{
public:
void print_hello(T var);
};
template <class T>
void Hello<T>::print_hello(T var)
{
std::cout << "Hello generic function " << var << "\n";
}
template <> //inline
void Hello<int>::print_hello(int var)
{
std::cout << "Hello specialized function " << var << "\n";
}
#endif
Run Code Online (Sandbox Code Playgroud)
paulo@aeris:~/teste/cpp/redef$ cat other.h
#include <iostream>
void other_func();
Run Code Online (Sandbox Code Playgroud)
paulo@aeris:~/teste/cpp/redef$ cat other.c
#include "other.h"
#include "hello.h"
void other_func()
{
Hello<char> hc;
Hello<int> hi; …Run Code Online (Sandbox Code Playgroud) 我有一个基于运行时返回特定设备的类。
struct ComponentDc;
struct ComponentIc;
typedef Device<ComponentDc> DevComponentDc;
typedef Device<ComponentIc> DevComponentIc;
template<class Component>
class Device{
Device<Component>* getDevice() { return this; }
void exec() { }
};
Run Code Online (Sandbox Code Playgroud)
在 中exec(),如果组件类型是,我想打印“Hello”,如果是,我想打印ComponentDc世界ComponentIc。此外,这些是可以创建 Device 的仅有的两种类型。
我该怎么做呢 ?
我有以下课程;
template<int N, int M, int K>
class BaumWelch
{
//lots of stuff
const TransitionMatrixTemplate<N, M> randomA()
{ //.... }
}
Run Code Online (Sandbox Code Playgroud)
现在我想专门randomA研究N = 1 的方法.我该怎么做?
我尝试了这个问题:模板化的一个方法的模板特化,但它似乎不适用于部分特化.这个问题:C++部分方法专业化似乎更相关,但它建议专门化整个类(在我的情况下这是非常大的).是否可以专门化整个班级,但实际上只专注于这一种方法?
我基本上试图做一个模板化专业化中讨论的内容,这个模板专门化来自模板化的类,除了我的TClass有多个模板参数,如下所示:
template < class KEY, class TYPE >
class TClass
{
public:
:
void doSomething(KEY * v);
:
};
template < class KEY, class TYPE >
void TClass<KEY, TYPE>::doSomething(KEY * v)
{
// do something
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是有效的,但我如何为一个模板参数定义一个专门的实现?我尝试添加这个:
template < class TYPE >
void TClass<int, TYPE>::doSomething(int * v)
{
// do something if KEY is int
}
Run Code Online (Sandbox Code Playgroud)
但是编译器抱怨"无法将函数定义与现有声明匹配"(VC2010)用于该方法/函数.
作为旁注:如果我同时专门化两个模板参数,它可以工作:
template < >
void TClass<int, char>::doSomething(int * v)
{
// do something if KEY is int and TYPE …Run Code Online (Sandbox Code Playgroud)