Does C ++ 11 support template class reflection?

I know a little bit of knowledge about the 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 reflection of the template class?

+4
source share
4 answers

Yes, and even better, you do not need to follow the instructions if(...){} else{}for this. You can use tag manager or specialization to avoid conditional statements. The following example uses tag dispatch.

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 area.

+5
source

Several variants:

  • SFINAE:

    template<class T>
    std::enable_if_t<std::is_base_of<M, T>>
    function(T* a)
    {
        a->function_m();
    }
    
    template<class T>
    std::enable_if_t<!std::is_base_of<M, T>>
    function(T* a)
    {
        a->function_o();
    }
    
  • or sending tags:

    namespace details {
        template<class T>
        void function(T* a, std::true_type) {
            a->function_m();
        }
    
        template<class T>
        void function(T* a, std::false_type) {
            a->function_o();
        }
    }
    template<class T>
    void function(T* a)
    {
        details::function(a, std::is_base_of<M, T>{});
    }
    
+3
source

, std::is_base_of<Base,Derived>:

template<class T>
void function(T * a) {
  if (std::is_base_of<M,T>::value) {
    a->function_m();
  } else {
    a->function_o();
  }
}

However, probably, it will cause a problem in this case, as function_m()and function_o()should have been called.

+1
source

What do you want to do in C ++ 17

template <typename T>
void function( T* a )
{
    if constexpr (std::is_base_of<M,T>::value)
        a->function_m();
    else
        a->function_o();
}

Full example: http://melpon.org/wandbox/permlink/MsHnYQNlBcRhTu2C As mentioned by @Fabio Fracassi

0
source

Source: https://habr.com/ru/post/1609877/


All Articles