将模板限制为仅某些类? [英] Restricting templates to only certain classes?
问题描述
在Java中,您可以限制泛型,以便参数类型只是特定类的子类。这样,泛型就可以知道类型上的可用函数。
In Java you can restrict generics so that the parameter type is only a subclass of a particular class. This allows the generics to know the available functions on the type.
我在带有模板的C ++中没有看到这一点。因此,有一种方法可以限制模板类型,如果不是,则智能感知如何知道< typename T>
可用的方法,以及传入的类型是否可以
I haven't seen this in C++ with templates. So is there a way to restrict the template type and if not, how does the intellisense know which methods are available for <typename T>
and whether your passed-in type will work for the templated function?
推荐答案
从C ++ 11开始,没有方法可以约束模板类型参数。但是,您可以使用 SFINAE 来确保仅针对特定类型实例化模板。请参见 std :: enable_if
的示例。您将要与 std :: is_base_of $ c一起使用$ c>
。
As of C++11, there is no way to constrain template type arguments. You can, however, make use of SFINAE to ensure that a template is only instantiated for particular types. See the examples for std::enable_if
. You will want to use it with std::is_base_of
.
例如,要为特定的派生类启用功能,您可以执行以下操作:
To enable a function for particular derived classes, for example, you could do:
template <class T>
typename std::enable_if<std::is_base_of<Base, T>::value, ReturnType>::type
foo(T t)
{
// ...
}
C ++工作组(尤其是第8学习组)目前正在尝试为该语言添加概念和约束。这将允许您指定模板类型参数的要求。请参阅最新的Concepts Lite建议。正如Casey在评论中提到的那样,Concepts Lite将作为技术规范与C ++ 14同时发布。
The C++ working group (in particular, Study Group 8) are currently attempting to add concepts and constraints to the language. This would allow you to specify requirements for a template type argument. See the latest Concepts Lite proposal. As Casey mentioned in a comment, Concepts Lite will be released as a Technical Specification around the same time as C++14.
这篇关于将模板限制为仅某些类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!