typedef 中的可变参数模板解包参数
Variadic template unpacking arguments in typedef
给定以下 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;
我问自己是否可以使用可变参数模板来完成。代码来自 Hypodermic IoC 容器。如何在保留它们之间的 &&
检查的同时解压它们?
只需像这样写一个 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{};
我还没有测试过,所以可能会有一些错别字,但我希望你能理解。
然后你这样使用它:
typedef and_<typename ArgResolver<Args>::IsResolvable...> IsSignatureRecognized;
它的工作方式相当简单,我们有通用的 class template <class...> and_
可以接受任意数量的类型。第一个特化检查包中的第一个参数,如果它为假,则无需继续,因为整个 and_
将为假。如果为真,那么我们将继续检查其余参数。一旦没有剩余的参数,没有参数的特化只是 returns true.
这是一个例子:
and_<t, t, f, t>::value
gives conditional<t::value, and_<t, f, t>, f>::type
因为条件为真,type
计算第二个参数 and_<t, f, t>
。同样对于下一个参数,我们得到:
and_<f, t>::value
gives conditional<f::value, and_<t>, f>::type
现在条件为假,所以 type
求值为第三个参数 f
,我们完成了模板实例化,::value
给我们 false
.
如果所有参数都为真,您最终将达到 and_<>
,我们专门将其设为 std::true_type
,因此 ::value
为我们提供 true
.
我希望这有助于阐明这段代码的工作原理。
在 C++17 中,你可以这样做:
using IsSignatureRecognized = BoolType<(ArgResolver<Args>::IsResolvable::value && ...)>;
之前,你必须自己制作一个可变参数'and
'。
给定以下 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;
我问自己是否可以使用可变参数模板来完成。代码来自 Hypodermic IoC 容器。如何在保留它们之间的 &&
检查的同时解压它们?
只需像这样写一个 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{};
我还没有测试过,所以可能会有一些错别字,但我希望你能理解。
然后你这样使用它:
typedef and_<typename ArgResolver<Args>::IsResolvable...> IsSignatureRecognized;
它的工作方式相当简单,我们有通用的 class template <class...> and_
可以接受任意数量的类型。第一个特化检查包中的第一个参数,如果它为假,则无需继续,因为整个 and_
将为假。如果为真,那么我们将继续检查其余参数。一旦没有剩余的参数,没有参数的特化只是 returns true.
这是一个例子:
and_<t, t, f, t>::value
gives conditional<t::value, and_<t, f, t>, f>::type
因为条件为真,type
计算第二个参数 and_<t, f, t>
。同样对于下一个参数,我们得到:
and_<f, t>::value
gives conditional<f::value, and_<t>, f>::type
现在条件为假,所以 type
求值为第三个参数 f
,我们完成了模板实例化,::value
给我们 false
.
如果所有参数都为真,您最终将达到 and_<>
,我们专门将其设为 std::true_type
,因此 ::value
为我们提供 true
.
我希望这有助于阐明这段代码的工作原理。
在 C++17 中,你可以这样做:
using IsSignatureRecognized = BoolType<(ArgResolver<Args>::IsResolvable::value && ...)>;
之前,你必须自己制作一个可变参数'and
'。