3

给定以下 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 容器。如何在打开它们的同时保留它们&&之间的支票?

4

2 回答 2

4

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

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

在此之前,您必须自己制作一个可变参数 ' and'。

于 2015-12-08T16:22:48.520 回答
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的。

我希望这有助于澄清这段代码是如何工作的。

于 2015-12-08T16:13:20.557 回答