I know a little knowledge about C++ 11 template. My intention is to have a template function as shown below:
template<class T>
void function(T * a) {
if (T belongs to class M) {
a->function_m();
} else {
a->function_o();
}
}
Does C++ 11 support this template class reflection?
Yes, and better yet, you don't need to perform if(...){} else{}
statements to do so. You can use tag dispatching or specializations to avoid the conditional statements. The following example uses tag dispatching.
Example:
#include <iostream>
#include <type_traits>
template <typename B, typename D>
void function( D* a )
{
function( a, typename std::is_base_of<B, D>::type{} );
}
template <typename T>
void function( T* a, std::true_type )
{
a->function_b();
}
template <typename T>
void function( T* a, std::false_type )
{
a->function_c();
}
struct B
{
virtual void function_b() { std::cout << "base class.\n"; }
};
struct D : public B
{
void function_b() override { std::cout << "derived class.\n"; }
};
struct C
{
void function_c() { std::cout << "some other class.\n"; }
};
int main()
{
D d;
C c;
function<B, D>( &d );
function<B, C>( &c );
}
This mechanism does not require both functions to be visible in the same scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With