模板类表达式参数重载

时间:2009-05-26 04:01:25

标签: c++ templates parameters overloading

嘿,我正在试图弄清楚是否可以用表达式参数“重载”模板类的deffinition。有点像下面的代码片段。

template<class T>
class Test
{
public:
    T testvar;

    Test()
    {
        testvar = 5;
        cout << "Testvar: " << testvar << endl;
    }
};

template<class T>
class Test<T, int num>
{
public:
    T testvar;

    Test()
    {
        testvar = 10;

        cout << "Testvar: " << testvar << endl;
        cout << "Param: " << num << endl;
    }
};

感谢。

编辑:为了记录,我试图用C ++做这个,如果那不明显......:)

2 个答案:

答案 0 :(得分:2)

模板允许使用默认模板参数,这些参数可以提供类似于您正在寻找的内容..

template<class T, int num = -1>
class Test
{
public:
    T testvar;

    Test()
    {
        testvar = (num == -1 ? 10 : 5);

        cout << "Testvar: " << testvar << endl;
        if ( num != -1 )
            cout << "Param: " << num << endl;
    }
};

答案 1 :(得分:1)

如果您希望只为Test指定一个模板参数,则需要将默认模板参数声明为Shmoopty suggests

也可以部分专门针对不同的参数值:

// This base template will be used whenever the second parameter is
// supplied and is not -1.
template<class T, int num = -1>
class Test
{
public:
    T testvar;

    Test()
    {
        testvar = 10;
        cout << "Testvar: " << testvar << endl;
        cout << "Param: " << num << endl;
    }
};

// This partial specialisation will be chosen
// when the second parameter is omitted (or is supplied as -1).
template<class T, int num>
class Test<T, -1>
{
public:
    T testvar;

    Test()
    {
        testvar = 5;
        cout << "Testvar: " << testvar << endl;
    }
};

这避免了对ifswitch语句的需要,这使得它稍微快一点(没有执行运行时测试)并且允许其他案例稍后以“附加部分”的形式“嫁接”专业化。 (虽然哪种方法更清楚是个人品味的问题。)

相关问题