Reputation: 528
I want to be able to do something like this:
template <typename template_type>
class awesome_class{
public:
void some_function(void){
// if (template_type == type_a)
cout << "I am of type_a and doing type_a specific methods";
// endif
cout << "I am not of type_a and doing my normal methods";
}
}
I would basically like to extend a templated class so that if it is of a type which includes a specific member variable then to run some optimized code which is possible due to the member variable, but if it's not of that type then just ignore that section of code.
Is this possible in C++? Or am I going about this totally wrong?
Edit: Me specializing the functions would basically require me to do so to nearly every function in the class. At that point, I might as well just make another class dedicated just for the type in question. Again, thank you though, learned something new and valuable which will likely come in handy for other situations!
Upvotes: 0
Views: 143
Reputation: 125
Why not use a variable like "int class_type" in base class. Then you can set the class_type value in every derived class.
class Base{
int class_type;
public:
void something();
};
class Derived: public Base{
...
Derived(){
class_type = derived_class_type /*Some enumerated value*/;
}
};
void Base::something(){
std::cout << class_type << std::endl;
}
Upvotes: 1
Reputation: 45674
Just specialize that one function:
template <typename template_type>
class awesome_class{
public:
void some_function(void){
cout << "I am not of type_a and doing my normal methods";
}
};
template<> void awesome_class<type_a>::some_function(void) {
cout << "I am of type_a and doing type_a specific methods";
}
Of course, if things are more complicated, you might have to use inheritance and SFINAE.
Upvotes: 7