jeudi 20 décembre 2018

is there any way to partial instance a c++ template

I have a template for some type, and some code in the template are not valid for all types, so I want to skip them when needed.

struct T1
{
    int getData(){return 1;}
};

struct T2
{
    string getData(){return "string";}
};

struct T3
{
    // no getData()
};

template<typename T>
void printData(T param)
{
    cout << param.getData() << endl;
}

int main() {

    T1 t1;
    T2 t2;
    T3 t3;

    printData(t1);
    printData(t2);
    printData(t3);  // fails for T3 has no getData
}

I want to know is there some way like this(pseudo code):

template<typename T>
void printData(T param)
{
    if(T != T3) // compile time check, instance on this condition
    {
        cout << param.getData() << endl;
    }
}

I have tried std::is_same but it did not work

Aucun commentaire:

Enregistrer un commentaire