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

标签 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();
  }
}

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

最佳答案

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

例子:

#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 );
}

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

关于c++ - C++ 11 是否支持模板类反射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32899259/

相关文章:

c++ - C++ 抽象类的问题(我可以在 Java 中完成,但不能在 C++ 中完成!)

C++11 即时构造不一致

c++ - 如何迭代 C++ 映射中的一组特定键?

c++ - 在 Windows 中不使用 Unicode 有什么缺点?

Scala 中的 C++ 风格私有(private)访问?

c++ - 非局部非内联变量的初始化 : does it take place strictly before the `main()` function call?

c++ - std::regex 的不一致行为

c++ - 为什么 std::string ("\x00") 报告长度为 0?

c++11 - 在使用 new[] 分配的数组上使用 avx 时出现段错误(核心转储)

c++ - 与列表初始化语法的自动分配混淆