Variadic模板在typedef中解压缩参数

问题描述 投票:3回答:2

给出以下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容器。如何在保持每个之间的&&检查的同时打开它们?

c++ c++11 variadic-templates hypodermic
2个回答
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

现在条件是假的,所以type评估第三个参数f,我们完成了实例化模板,::value给了我们false

如果所有参数都是真的,你最终会达到我们专门为and_<>std::true_type,以便::value给我们true

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


4
投票

在C ++ 17中,您可以:

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

之前,你必须自己做一个变量'and'。

© www.soinside.com 2019 - 2024. All rights reserved.