[英]Variadic template unpacking arguments in typedef
Given the following C++ typedef
expression 给出以下C ++ typedef
表达式
template <bool> struct BoolType : std::true_type {};
template <> struct BoolType< false > : std::false_type {};
typedef BoolType< ArgResolver< Arg1 >::IsResolvable::value && ArgResolver< Arg2 >::IsResolvable::value > IsSignatureRecognized;
I was asking myself if it could be done with a variadic template. 我问自己是否可以使用可变参数模板完成。 The code comes from Hypodermic IoC container. 代码来自Hypodermic IoC容器。 How can I unpack them while retaining the &&
check between each of them? 如何在保持每个之间的&&
检查的同时解压缩它们?
In C++17, you may do: 在C ++ 17中,您可以:
using IsSignatureRecognized = BoolType<(ArgResolver<Args>::IsResolvable::value && ...)>;
before, you have to make an variadic ' and
' by yourself. 之前,你必须自己做一个变量' and
'。
Just write up an and_
metafunction like this: 只需编写一个这样的and_
元函数:
template <class ... Bools>
struct and_;
template <class Bool, class ... Bools>
struct and_<Bool, Bools...> : std::conditional<
Bool::value, and_<Bools...>, std::false_type>::type{};
template <>
struct and_<> : std::true_type{};
I haven't tested this so there may be a couple of typos, but I hope you get the idea. 我没有测试过,所以可能会有一些错别字,但我希望你能得到这个想法。
Then you use it like this: 然后你像这样使用它:
typedef and_<typename ArgResolver<Args>::IsResolvable...> IsSignatureRecognized;
The way it works is fairly simple, we have the generic class template <class...> and_
which accepts any number of types. 它的工作方式非常简单,我们有通用类template <class...> and_
,它接受任意数量的类型。 The first specialization checks the first argument in the pack, if it's false there's no need to continue since the whole and_
will be false. 第一个特化检查包中的第一个参数,如果它是假的,则不需要继续,因为整个and_
将为false。 If it's true then we continue checking the rest of the parameters. 如果是真的那么我们继续检查其余的参数。 Once there are no more parameters left, the specialization with no parameters simply returns true. 一旦没有剩下的参数,没有参数的专门化只返回true。
Here's an example: 这是一个例子:
and_<t, t, f, t>::value
gives conditional<t::value, and_<t, f, t>, f>::type
Because the condition is true, type
evaluates to the second parameter and_<t, f, t>
. 因为条件为true,所以type
计算为第二个参数and_<t, f, t>
。 Similarly for the next parameter, we get to: 类似地,对于下一个参数,我们得到:
and_<f, t>::value
gives conditional<f::value, and_<t>, f>::type
Now the condition is false so type
evaluates to the third parameter f
and we are done instantiating templates and ::value
gives us false
. 现在条件为假,因此type
求值为第三个参数f
,我们完成了实例化模板, ::value
给出了false
。
If all the parameters are true you will eventually reach and_<>
which we specialized to be std::true_type
so that ::value
gives us true
. 如果所有参数都为真,那么最终将到达and_<>
,我们专门将其作为std::true_type
以便::value
为true
。
I hope that helps clarify how this code works. 我希望这有助于澄清此代码的工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.