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

how to carry out few different set of instruction for string datatype in a template?

本文关键字:几组 指令 数据类型 字符串 执行      更新时间:2023-10-16

我在为所有booldoubleintstring调用的类中有一个模板成员函数。我想执行上面提到的所有数据类型通用的一些指令。但对于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 */ }

编辑:显然,我没有注意到其中的"成员函数"部分。解决方案是添加一个额外的间接寻址,一个专门用于字符串并在当前函数末尾调用的函数。