gpt4 book ai didi

c++ - 如何在模板中对字符串数据类型执行几组不同的指令?

转载 作者:太空狗 更新时间:2023-10-29 20:06:41 24 4
gpt4 key购买 nike

我在一个类中有一个模板成员函数,它为所有 bool 调用, double , intstring .我想执行一些对上述所有数据类型通用的指令。但是对于 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 Method 模式)。

在这里,您可以通过将函数的最后几行移动到它自己的函数中来轻松完成此操作,该函数可以专门用于某些数据类型。请记住,当涉及到功能时,overloading should be preferred to template specialization .

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 是一个包含一个值的类模板,如果它的两个参数是同一类型,则该值为真,在 TR1、Boost 和 C++0x 中可用。仅当 if 子句中的代码对您实例化模板所用的每种数据类型都有效时,此解决方案才有效。例如,如果您在 if block 中使用 string 的成员函数,则在使用其他数据类型实例化该函数时编译将失败,因为您无法调用方法原始类型。

关于c++ - 如何在模板中对字符串数据类型执行几组不同的指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6624844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com