Template class expression parameter overloading

Hey I'm trying to figure out if it's possible to "overload" the division of a template class using expression parameters. Look like the following piece of code.

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

      

Thanks.

Edit: for the record, I'm trying to do this with C ++ if it wasn't obvious ... :)

0


a source to share


2 answers


Templates allow you to use default template options, which can provide something similar to what you are looking for.



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

      

+2


a source


If you only want to specify one template argument for Test

, you will need to declare a default template parameter, as Shmoopty suggests .

It is also possible to partially specialize for different parameter values:



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

      

This avoids the need for statements, if

or switch

makes it a little faster (no runtime testing is done) and allows additional cases to be "grafted" later in the form of additional partial specializations. (Although which approach is clearer, this is a matter of personal taste.)

+1


a source







All Articles