Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ 11 support template class reflection?

Tags:

c++

c++11

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?

like image 462
JoJo Avatar asked Jan 08 '23 11:01

JoJo


1 Answers

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.

like image 79
bku_drytt Avatar answered Jan 10 '23 01:01

bku_drytt