4

鉴于以下情况:

template <typename T0,typename T1,typename T2 , typename T3 , typename T4>
class Tuple
{
private:
    T0 v0;
    T1 v1;
    T2 v2;
    T3 v3;
    T4 v4;

public:
    void f()
    {
        cout << v0 << "," << v1 << "," << v2 << "," << v3 << "," << v4 << endl;
    }

};

我想创建一个只有两个int-s 的部分类,那么我必须像这样专门化:

class NullType { };  // create an empty class
template <typename T0, typename T1>
class Tuple<T0,T1,NullType,NullType,NullType >
{
    private:
        T0 v0;
        T1 v1;
    public:
        void func()
        {
            cout << "i'm a specialization" << endl;
        }
};

但是这个实现需要我做:

Tuple<int,int,NullType,NullType,NullType> b;

所以这很丑:)

有没有另一种方法来实现部分专业化而不定义另一个(空)类,所以我可以这样做:Tuple<int,int> b1;

4

2 回答 2

7

您可以使 T2 到 T4 默认模板参数并使用void而不是空NullType类,例如:

template <typename T0,typename T1,typename T2=void , typename T3=void , typename T4=void> class Tuple { private:
    T0 v0;
    T1 v1;
    T2 v2;
    T3 v3;
    T4 v4;

public:
    void f()
    {
        cout << v0 << "," << v1 << "," << v2 << "," << v3 << "," << v4 << endl;
    }

};

template <typename T0, typename T1> class Tuple<T0,T1,void,void,void > {
    private:
        T0 v0;
        T1 v1;
    public:
        void func()
        {
            cout << "i'm a specialization" << endl;
        } };

int main(int argc, char** argv) {
    Tuple<int,int> myTuple;
    myTuple.func(); 
    return 0;
}

有关工作示例,请参见此处。

编辑:或者,您可以将boost::tuple或 std::tuple 与 C++11 一起使用 :)

于 2012-08-27T12:56:53.777 回答
2

如果您的编译器支持 C++11 模板别名,这很容易做到:

template <typename T, typename U>
using tuple2 = tuple<T,U,NullType,NullType,NullType>;
于 2012-08-27T13:21:29.953 回答