我对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/