简体   繁体   English

用于特定类型推导的功能模板专门化

[英]Function template specialization for derivation of a specific type

class base
{
};

class derived
{
};

template<class T> void foo() {}


int main()
{
    foo<int>();
    foo<derived>();
}

I want to specialize foo for T = derivation of base . 我想将foo专用于T = base派生。 Is this possible or do I need to specialize for base itself? 这是否可能,或者我是否需要专门研究base本身?

You can combine boost::enable_if and boost::is_base_of, as is documented in the manual for boost::enable_if . 您可以将boost :: enable_if和boost :: is_base_of结合使用,如boost :: enable_if手册中所述

template <class T>
T foo(typename enable_if<boost::is_base_of<base,T> >::type* dummy = 0); 

One option would be to use boost type traits (or if feeling brave, look at the source of that library). 一种选择是使用增强类型特征 (或者,如果感到勇敢,请查看该库的源代码)。

At compile time you can detect if a type inherits from another type and so choose an appropriate implementation. 在编译时,您可以检测一个类型是否从另一个类型继承,因此选择合适的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM