Variadic模板在typedef中解压缩参数

时间:2015-12-08 16:07:46

标签: c++ c++11 variadic-templates hypodermic

给出以下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容器。如何解压缩它们,同时保留每个之间的&&检查?

2 个答案:

答案 0 :(得分:4)

在C ++ 17中,您可以这样做:

using IsSignatureRecognized = BoolType<(ArgResolver<Args>::IsResolvable::value && ...)>;

之前,你必须制作一个可变的&#39; and&#39;你自己。

答案 1 :(得分:3)

只需编写一个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;

它的工作方式非常简单,我们有通用类template <class...> and_,它接受​​任意数量的类型。第一个特化检查包中的第一个参数,如果它是错误的,那么由于整个and_都是假的,所以不需要继续。如果它是真的,那么我们继续检查其余的参数。一旦没有剩下的参数,没有参数的专门化只会返回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

现在条件为false,因此type评估第三个参数f,我们完成了实例化模板,::value给了我们false

如果所有参数均为真,那么您最终会获得我们专门为and_<>的{​​{1}},以便std::true_type为我们提供::value

我希望这有助于澄清此代码的工作原理。