c++ - Is it possible to have conditional declaration of methods and variables in templated classes? -


i trying make class can have functions , members controlled template argument. thinking of this.

template<int control> class controlleddeclaration { public:     if(1 == control)         int get() { return 0; }     else if(2 == control)         char* get() { return "get"; }     else if (3 == control)         bool get() { return true; } };  void test_template() {     controlleddeclaration<1> c_int;     controlleddeclaration<2> tx_int;     controlleddeclaration<3> b_int; } 

if possible, how it?

the approach use along lines of specializing details in traits class , provide interface using template. in trivial example there isn't benefit of using traits rather specializing actual type in general customizing few points of variations easier using traits specializations.

template <int> struct controldeclarationtraits; template <> struct controldeclarationtraits<1> {     typedef int type;     static int value() { return 0; }; };  template <> struct controldeclarationtraits<2> {     typedef char const* type;     static char const* value() { return "get"; } };  template <> struct controldeclarationtraits<3> {     typedef bool type;     static bool value() { return true; } };  template<int control> class controlleddeclaration { public:     typename controldeclarationtraits<control>::type get() {         return controldeclarationtraits<control>::value();     } }; 

btw, type of string literals char const[n] (for suitable n) , not char[n], i.e., can't use string literal initialize char*. work because deemed necessary support existing code assign string literals char* lie: trying assign value of values causes undefined behavior. making pointer const makes obvious content isn't meant modified.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -