lundi 27 avril 2015

How in C++ use templates to call specific members of supplied type

Lets assume we have to classes

struct A
{
    int x = 1;
}
struct B
{
    int y = 2;
}

I want to have template that will return value of member (in a case of A I want to return value of "x", in case of B I want to return value of "y").

Example call:

const auto myVariable = f<A>();

or

A a;
const auto myVariable = f(a);

I don't want to have 2 template specializations - ideally it would be one template with some kind of "if statement", but maybe it is not possible?

It may be written with C++ 11 (but not with C++ 14).

Generally how you are using templates when you have such problems - quite big template and only in one or two places you need to take values from different members - which may be deducted based of type of that variable.

Aucun commentaire:

Enregistrer un commentaire