0

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

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++ 来做到这一点...... :)

4

2 回答 2

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;
    }
};
于 2009-05-26T04:16:01.770 回答
1

如果您希望能够只为 指定一个模板参数Test,则需要按照Shmoopty 的建议声明一个默认模板参数。

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

// 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;
    }
};

这避免了对iforswitch语句的需求,这使得它稍微快了一点(不执行运行时测试),并允许稍后以额外的部分专业化的形式“嫁接”额外的案例。(尽管哪种方法更清晰是个人品味的问题。)

于 2009-05-26T12:33:05.007 回答