问题描述
我想知道C ++ 0x是否提供任何内置功能来检查可变参数模板的参数包是否包含特定类型.今天,如果您使用boost :: mpl :: vector来代替可变参数模板,可以使用boost ::: mpl :: contains完成此操作.但是,它具有严重的编译时间开销.我想,C ++ 0x对std :: is_same具有编译器级别的支持.因此,我在考虑是否在编译器 中也支持以下概括.
I was wondering if C++0x provides any built-in capabilities to check if a parameter pack of a variadic template contains a specific type. Today, boost:::mpl::contains can be used to accomplish this if you are using boost::mpl::vector as a substitute for variadic templates proper. However, it has serious compilation-time overhead. I suppose, C++0x has compiler-level support for std::is_same. So I was thinking if a generalization like below is also supported in the compiler.
template <typename... Args, typename What>
struct is_present
{
enum { value = (What in Args...)? 1 : 0 };
};
推荐答案
不,您必须对可变参数模板使用(部分)专业化,才能进行如下编译时计算:
No, you have to use (partial) specialization with variadic templates to do compile-time computations like this:
#include <type_traits>
template < typename Tp, typename... List >
struct contains : std::true_type {};
template < typename Tp, typename Head, typename... Rest >
struct contains<Tp, Head, Rest...>
: std::conditional< std::is_same<Tp, Head>::value,
std::true_type,
contains<Tp, Rest...>
>::type {};
template < typename Tp >
struct contains<Tp> : std::false_type {};
可变参数模板只有另一种内在运算,这是sizeof运算符的特殊形式,用于计算参数列表的长度,例如:
There is only one other intrinsic operation for variadic templates and that is the special form of the sizeof operator which computes the length of the parameter list e.g.:
template < typename... Types >
struct typelist_len
{
const static size_t value = sizeof...(Types);
};
boost mpl从何而来?我希望您不只是在这里做假设. Boost mpl使用诸如惰性模板实例化的技术来尝试减少编译时间,而不是像朴素的模板元编程那样爆炸.
Where are you getting "it has serious compilation-time overhead" with boost mpl from? I hope you are not just making assumptions here. Boost mpl uses techniques such as lazy template instantiation to try and reduce compile-times instead of exploding like naive template meta-programming does.
这篇关于检查参数包是否包含类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!