我知道一点关于C++ 11模板的知识。我的意图是有一个模板函数,如下所示:
template<class T>
void function(T * a) {
if (T belongs to class M) {
a->function_m();
} else {
a->function_o();
}
}C++ 11支持这个模板类反射吗?
发布于 2015-10-02 09:48:39
是的,而且更好的是,您不需要执行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 );
}此机制不要求两个函数在同一范围内可见。
发布于 2015-10-02 16:56:13
有几种选择:
模板函数,T>> function(T* a) {a-> std::enable_if_t> function(T* a) {a->std::enable_if_t<_o();}
命名空间详情{模板空函数(T* a,std::true_type) { a->function_m();}模板空函数(T* a,std::false_type) { a->function_o();}}模板空函数(T* a) { details::function(a,std::is_base_of{});}
发布于 2015-10-02 09:37:07
是的,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();
}
}但是,在这种情况下可能会造成问题,因为function_m()和function_o()都需要是可调用的。
https://stackoverflow.com/questions/32899259
复制相似问题