具有std :: is_base_of的派生类的C ++模板函数 [英] C++ template function for derived class with std::is_base_of
问题描述
如果给定类型的函数是从另一个函数派生的,而对于所有其他情况,则创建其他函数,我会遇到问题.我的代码:
I've got problem with creating function that for given type, if it's derived from other one do something and for all other cases do something other. My code:
class BaseClass {};
class DerivedClass : public BaseClass {};
template <typename T>
void Function(typename std::enable_if<std::is_base_of<BaseClass, T>::value, T>::type && arg) {
std::cout << "Proper";
}
template <typename T>
void Function(T && arg) {
std::cout << "Improper";
}
void test() {
Function(DerivedClass{});
}
对于类DeriviedClass
和其他基于BaseClass
的类,我想调用函数 couting Proper
,但是它是 couts Improper
.有什么建议吗?
For class DeriviedClass
and other based on BaseClass
I'd like to call function couting Proper
, but it couts Improper
. Any suggestions?
推荐答案
正如问题注释中所提到的那样,SFINAE表达式无法像您那样使用.
它应该是这样的:
As mentioned in the comments to the question, SFINAE expressions won't work the way you did it.
It should be instead something like this:
template <typename T>
typename std::enable_if<std::is_base_of<BaseClass, T>::value>::type
Function(T && arg) {
std::cout << "Proper" << std::endl;
}
template <typename T>
typename std::enable_if<not std::is_base_of<BaseClass, T>::value>::type
Function(T && arg) {
std::cout << "Improper" << std::endl;
}
SFINAE表达式将启用或禁用Function
,具体取决于BaseClass
是T
的基础.在这两种情况下,返回类型均为void
,因为如果未定义,则它是std::enable_it
的默认类型.
在 coliru 上查看.
SFINAE expressions will enable or disable Function
depending on the fact that BaseClass
is base of T
. Return type is void
in both cases, for it's the default type for std::enable_it
if you don't define it.
See it on coliru.
存在其他有效的替代方法,其中一些已在其他答案中提及.
Other valid alternatives exist and some of them have been mentioned in other answers.
这篇关于具有std :: is_base_of的派生类的C ++模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!