如果我想创建一个模板类,并根据模板参数的typeid执行不同的操作,那么我该如何编码?如何针对模板类中的不同模板参数执行不同的操作?
例如,我有以下模板类,其中我想根据它是一个int还是一个字符串来初始化成员字段数据。
#include <string>
template <class T>
class A
{
private:
T data;
public:
A();
};
// Implementation of constructor
template <class T>
A<T>::A()
{
if (typeid(T) == typeid(int))
{
data = 1;
}
else if (typeid(T) == typeid(std::string))
{
data = "one";
}
else
{
throw runtime_error("Choose type int or string");
}
}
但是,此代码不会编译,但具有以下主文件。
#include "stdafx.h"
#include "A.h"
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
A<int> one;
return 0;
}
的错误是:错误C2440: '=':不能从 '为const char [2]' 到 'INT',这意味着代码转换实际上是检查其他-if语句为一个int,甚至尽管它永远无法达到这部分代码。
接下来,按照这个例子(Perform different methods based on template variable type),我尝试了下面的A.h文件,但是我有几个链接器错误提到A(void)已经在A.obj中定义。
#include <string>
template <class T>
class A
{
private:
T data;
public:
A();
~A();
};
// Implementation of constructor
template <>
A<int>::A()
{
data = 1;
}
template <>
A<std::string>::A()
{
data = "one";
}
有没有人知道如何让这段代码启动并运行?我也意识到,在模板类中使用这样的if-else语句可能会从模板中删除权力。有没有更好的方法来编码?
编辑:
#pragma once
#include <string>
// Class definition
template <class T>
class A
{
public:
A();
~A();
private:
T data;
};
// Implementation of initialization
template < class T >
struct initial_data
{
static T data() { throw runtime_error("Choose type int or string"); }
};
template <>
struct initial_data<int>
{
static int data() { return 1; }
};
template <>
struct initial_data<std::string>
{
static std::string data() { return "one"; }
};
// Definition of constructor
template <class T>
A<T>::A()
: data(initial_data<T>::data())
{
}
和以下主要:
#include "stdafx.h"
#include "A.h"
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
A<int> ione;
return 0;
}
链接器错误我现在得到的是:与托斯滕(如下图),我现在有以下阿文件的讨论后测试模板4.obj:错误LNK2019:函数_wmain中引用的无法解析的外部符号“public:__thiscall A ::〜A(void)”(?? 1?$ A @ H @@ QAE @ XZ)
1)不要使用'_tmain'废话和朋友。 2)在模板中使用'typeid'有什么意义?因为没有'int :: operator =(const char *)',所以代码根本不会编译为'T = int' ... 3)请编译错误的测试用例。 – Griwes
作为第二个例子的模板专门化是要走的方式恕我直言......你是否在你的头文件中加入了包容守卫?从链接器错误,它看起来像你没有。 – Naveen
我想你可以使用SFINAE。有了'enable_if'和'is_same',你可以有不同的基于模板参数的成员funcs。 – jrok