C++ 11是否支持模板类反射?

JoJ*_*oJo 4 c++ c++11

我对C++ 11模板有一点了解.我的目的是拥有一个模板函数,如下所示:

template<class T>
void function(T * a) {
  if (T belongs to class M) {
    a->function_m();
  } else {
    a->function_o();
  }
}
Run Code Online (Sandbox Code Playgroud)

C++ 11是否支持此模板类反射?

bku*_*ytt 5

是的,更好的是,您不需要执行if(...){} else{}语句来执行此操作.您可以使用标记分派或特化来避免条件语句.以下示例使用标记分派.

例:

#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 );
}
Run Code Online (Sandbox Code Playgroud)

此机制不要求两个函数在同一范围内可见.