如何对模板中的字符串数据类型执行几组不同的指令
how to carry out few different set of instruction for string datatype in a template?
我在为所有bool
、double
、int
和string
调用的类中有一个模板成员函数。我想执行上面提到的所有数据类型通用的一些指令。但对于String
,最后几行代码是不同的。因此,有人能建议我在同一个模板函数中实现这一点的更好方法吗。
template< class T>
xyz (t* a)
{
//few lines are common for all types for data
//last 3 lines of code is different for Strings
}
解决方案通常是对常见行为进行因子分解,并提供专门化算法某些部分的方法(请参阅模板方法模式(。
在这里,您可以通过在自己的函数中移动函数的最后一行来很容易地做到这一点,该函数可以专门用于某些数据类型。请记住,当涉及到函数时,重载应该优先于模板专用化。
template <class T>
void xyz(T * a)
{
//few lines are common for all types for data
xyz_finish(a);
}
template <class T>
void xyz_finish(T * a)
{
// default case (can be empty)
}
void xyz_finish(std::string * s)
{
// string case
}
当然,你的函数应该有一个比我使用的名称更具描述性的名称。。。
您还可以执行对称操作:移动函数中的常见行为,并重载"顶级"函数:
template <class T>
void xyz(T * a)
{
common_behavior(a);
}
void xyz(std::string * s)
{
common_behavior(s);
// code specific to strings
}
template <class T>
void common_behavior(T * a)
{
//few lines that are common for all types for data
}
如果您不想要或无法创建其他函数,您可以测试参数的类型:
template <class T>
void xyz(T * a)
{
// common code
if (is_same<T, std::string>::value)
{
//code for strings
}
}
is_same
是一个类模板,包含一个值,如果它的两个参数是相同的类型,则该值为true,在TR1、Boost和C++0x中可用。只有当if
子句中的代码对实例化模板时使用的每种数据类型都有效时,此解决方案才能工作。例如,如果在if
块中使用string
的成员函数,则在用其他数据类型实例化该函数时,编译将失败,因为您无法调用基元类型上的方法。
您可以将最后3行移到某个函数中,并使用C++函数重载,即一行用于bool,第二行用于int等。
struct Foo {
template <typename T>
voud foo (T *) {
foo ();
}
void foo (string *) {
foo ();
bar ();
}
private:
void foo () {
}
};
或
struct Foo {
template <typename T>
void foo (T * t) {
do_foo (t);
}
void foo (string * s) {
do_foo (s);
bar (s);
}
private:
template <typename T>
void do_foo (T *) {
}
};
您可以在类的外部显式地专门化Foo::Foo。
tempalte <> void Foo :: foo (string *) {}
这似乎可以被不正当地利用,尽管。。。
您只需要专门化字符串模板,如下所示:
template<> xyz(string* a) { /* code here, including modified lines */ }
编辑:显然,我没有注意到其中的"成员函数"部分。解决方案是添加一个额外的间接寻址,一个专门用于字符串并在当前函数末尾调用的函数。
- 在C++中,如何通过几种类型从元组中选择多个元素
- 使用内在指令的欧几里得距离
- 用于在一维数组上嵌套循环操作的正确 openmp 指令
- 如何从数组中仅返回几个值
- 我有一个包含几个重复元素的数组,我想找到最接近数组末尾的重复元素的索引
- LLVM:如何将一些指令/内在的指令转换为几个链式说明
- 如何读取从文本文件到几个数组的不同类型的数据?C
- 使用C - CIN获取几个整数数字,然后将它们放入数组中
- 使用欧几里得公式求全毕达哥拉斯三元组
- 为什么sleep in函数忽略了程序中的几个顺序指令
- 在c++中的一个函数中返回几个数组和变量(如MATLAB)
- 使用OpenMP分配数组的特殊指令
- 关于C++中数组的几个问题
- 如何创建一个一维数组来容纳几个二维数组
- 我正在尝试设置几个不同的多维数组,但无法弄清楚为什么这不起作用
- 添加数组所有元素的 SSE 指令
- 使用 int 数组作为键的二叉树(欧几里得距离)
- 如何截断前几个字符字符数组 C++
- 寻找毕达哥拉斯三元组:欧几里得公式
- 如何对模板中的字符串数据类型执行几组不同的指令