I found a similar question here but it does not specifically answer my question. I have a simple class template that only takes one parameter. It does not store any member variables and has no methods other than a simple constructor. Based on the type passed in I need to branch my logic within the constructor. A simple version shell of the class would look like this as to what I'm trying to do. The class will take Type t
do some processing and will store the results into an std::string
by reference.
template<class Type>
struct Test {
Test( Type t, std::string& str )
static_assert( std::is_arithmetic<Type>::value, "Arithmetic type required." );
if ( std::is_arithmetic<Type>::value ) { // check if type is arithmetic
// some variables here
if ( std::is_integral<type>::value ) {
// some code for integral types
} else {
// some other code for arithmetic non integral types (floating point types)
}
str = // some code.
} else {
// possibly throw some exception
}
};
Is this an adequate way to resolve branch decisions based on data type
? Or is there a more desirable-efficient way of doing this?
- I could have a default constructor with a few member variables and overload 2 or 3 functions
- I could do partial specialization of the class (not preferred).
- I could just eliminate the "class-struct" altogether and do this as a function template, however, I would prefer to instantiate objects of this type.
Aucun commentaire:
Enregistrer un commentaire