lets assume have 2 classes
struct { int x = 1; }; struct b { int y = 2; };
i want have template return value of member (in case of want return value of "x", in case of b want return value of "y").
example call:
const auto myvariable = f<a>();
or
a a; const auto myvariable = f<a>(a);
i don't want have 2 template specializations - ideally 1 template kind of "if statement", maybe not possible?
it may written c++11 (but not c++14).
generally how using templates when have such problems - quite big template , in 1 or 2 places need take values different members - may deduced based of type of variable.
problem: unnecessary not allowed modify classes , b
just in case ask template because want switch between , b @ compile time...and have reason not typedef or b directly...
struct { int x; }; struct b { int y; }; struct a1 : public { int get() const { return x; } }; struct b1 : public b { int get() const { return y; } }; // begin possible shortcut avoiding template below: #ifdef use_a typedef a1 bar; #endif #ifdef use_b typedef b1 bar; #endif // end possible shortcut. template <class _base> struct compiletimeaorb : public _base { int get() const { return _base::get(); } }; #define use_a //#define use_b #ifdef use_a typedef compiletimeaorb<a1> foo; #endif #ifdef use_b typedef compiletimeaorb<b1> foo; #endif
edit: since , b cannot changed, introduced a1, b1 ;)