[英]Using conditional definitions with variadic templates
If I have a template function which takes a known number of template arguments, I can use the enable_if
statement along with things like is_base_of
to limit the legal types. 如果我有一个使用已知数量的模板参数的模板函数,则可以使用enable_if
语句以及is_base_of
类的is_base_of
来限制合法类型。 For example: 例如:
template <typename T>
typename enable_if<is_base_of<BaseClass, T>::value, void>::type
function() {
// do stuff with T, which is ensured to be a child class of BaseClass
}
Now suppose we want to do the same thing for a variadic template - check to make sure all types are children of a specific base class. 现在假设我们要对可变参数模板执行相同的操作-检查以确保所有类型都是特定基类的子代。
template <typename... T>
/* What goes here? */
function() {
// do stuff with the T types, which are ensured to be child classes of BaseClass
}
How would you go about writing this conditional definition? 您将如何编写此条件定义?
You may use the following type_traits: 您可以使用以下type_traits:
template <typename Base, typename T, typename... Ts>
struct are_base_of :
std::conditional<std::is_base_of<Base, T>::value, are_base_of<Base, Ts...>,
std::false_type>::type
{};
template <typename Base, typename T>
struct are_base_of<Base, T> : std::is_base_of<Base, T> {};
And then use 然后用
template <typename... Ts>
typename std::enable_if<are_base_of<BaseClass, Ts...>::value, void>::type
function() {
// do stuff with Ts, which is ensured to be a child class of BaseClass
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.