c++ - Calling different base class constructors depending on input parameter value -
i have following scenario:
depending on input value derived
class's constructor need call different base
class constructor.
such as:
struct base { base() : v(0) {} base(int _v) : v(_v) {} int v; }; struct derived { derived(int v) /* if v == 42 call base() else call base(int) */ {} }; int main() { derived f2(42); derived f1(1); }
with current knowledge of c++ think not possible, ask community if aware of hacks, or dirty code make feasible. please don't let simple int
s misguide you, real life scenario more complex. feel free mix in c++11 magic.
edit: also, don't want use "init" function depending on value of parameter initializes differently things.
this indeed quite strange request, maybe should reconsider general approach. meaning of particular 42
value? what question 42 answer? maybe should have 2 sibling derived
s, or subclass derived
x==42
case or x!=42
case, etc. or maybe 42
comes different-type object , can use separate constructor type?
but if indeed want accomplish have asked, 1 possible approach have 2 somehow different constructors in derived
, "named constructor" (static function) route between them. (did not check compilability, idea should clear):
struct derived { private: derived(int x): base(x) {} derived(): base() {} public: static derived constructderived(int x) { if (x==42) return derived(); else return derived(x); } }; // usage derived = derived::constructderived(42); derived b = derived::constructderived(43);
for need copy constructor, can return pointers etc.
another approach, if value of 42 fixed @ compile time, use templates , specialize constructor or class particular value of 42.
another approach think should work, require base class copy- or move-constructible:
struct derived { derived(int x): base( (x == 42)? base() : base(x) ) {} };
Comments
Post a Comment