In C ++ 11, I would like to have a member variable in the class and a constructor to initialize it only if its default value was selected (only for supported types such as int, of course).
What are the recommended ways to achieve this (promotion allowed)?
Sort of:
template< int _x = -1 > struct C { C() {} // only available if _x != -1 C( int x ) : x( x ) {} // only available if _x == -1 // more methods that are common for all _x and refer to _x / x private: int x; // only available if _x == -1 // more members that are common for all _x };
Or, in another way: to optimize size and speed, I would like to use the compile-time constant instead of the value stored in the member variable if a different value was selected than the default template.
-
Here is an example to make everything clearer:
template< int _size = -1 > struct Block { Block() { buf = mmap( _size, ... ); } // exists only when size!=-1 Block( int s ) { buf = mmap( size = s, ... ); } // exists only when size==-1 ~Block() { munmap( buf, getSize() ); } // should use the correct size int getSize() const { return ???; } // gets _size if !=-1, size otherwise // other methods that use buf and getSize() private: void *buf; const int size; // only exists for size == -1! };
This partially resolves:
template< int _x > struct X { int getX() const { return _x; } }; template<> struct X< -1 > { X( x ) : x( x ) {} int getX() const { return _x; } private: int x; }; template< int _x = -1 > struct C : X< _x > { C() {}
But what about C constructors and other / nicer solutions are available?
source share