17

如果我有两个可变参数模板参数,A并且B,我如何在编译时确保所有成员的 A类型也是B(以相同顺序)的子集的类型?

人为的例子:

template<typename...A>
struct Foo {
  template<typename...B>
  static void bar()
  {
  }
}

...

Foo<Apple, Orange>:: template bar<Apple, Orange, Grape>(); // this compiles
Foo<Apple, Orange>:: template bar<Orange, Grape>(); // this doesn't
4

1 回答 1

12

对于我不知道的一般子集,但是如果您可以保证它B的形式为A..., More...,那么这可能会:

#include <functional>
#include <tuple>

template <typename ...A>
struct var_equal : std::false_type { };

template <typename A1, typename ...Aother, typename B1, typename ...Bother>
struct var_equal<std::tuple<A1, Aother...>, std::tuple<B1, Bother...>>
{
  static const bool value = std::is_same<A1, B1>::value && var_equal<std::tuple<Aother...>, std::tuple<Bother...>>::value;
};

template <typename ...B>
struct var_equal<std::tuple<>, std::tuple<B...>> : std::true_type { };


template<typename...A>
struct Foo {
  template<typename...B>
  static void bar()
  {
    static_assert(var_equal<std::tuple<A...>, std::tuple<B...>>::value, "Hello");
  }
};

(对不起,var_equal这个名字很糟糕。它应该被称为更合适的名字,比如initial_equal。)


更新:这是由Luc Danton详细制定的通用解决方案(请参阅此处查看其精美样式的代码):

#include <type_traits>
#include <tuple>

template <typename Sub, typename Super>
struct subset_of : std::false_type {};

template<typename Same, typename... AOther, typename... BOther>
struct subset_of<std::tuple<Same, AOther...>, std::tuple<Same, BOther...>>
: subset_of<
    std::tuple<AOther...>
    , std::tuple<BOther...>
> {};

template<typename ADifferent, typename BDifferent, typename... AOther, typename... BOther>
struct subset_of<std::tuple<ADifferent, AOther...>, std::tuple<BDifferent, BOther...>>
: subset_of<
    std::tuple<ADifferent, AOther...>
    , std::tuple<BOther...>
> {};

template<typename... B>
struct subset_of<std::tuple<>, std::tuple<B...>>: std::true_type {};

template<typename... A>
struct Foo {
    template<typename... B>
    static void bar()
    {
        static_assert(subset_of<std::tuple<A...>, std::tuple<B...>>::value, "Hello");
    }
};

测试用例:

struct Apple{}; struct Orange{}; struct Grape{};

int main()
{
    Foo<Apple, Orange>::bar<Apple, Orange, Grape>();               // this compiles
    Foo<Apple, Orange>::bar<Grape, Apple, Grape, Orange, Grape>(); // this also compiles
    Foo<Apple, Orange>::bar<Orange, Grape>();                      // this doesn't
}
于 2011-07-08T08:43:32.120 回答