Deduce参数包而不将其明确作为模板参数传递?

时间:2011-05-17 15:52:25

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

原谅任何对C ++类型演绎的无知,但我希望能够随身携带参数包的定义,以便稍后我可以测试内部类型。这可能吗?类似的东西:

template <typename... Args> struct Entity {

    struct Inner {
        typedef Args... entity_args_t;
    };

    struct SomeOtherInner {
        typedef Args... entity_args_t;
    };
};

struct ThingA : Entity<int, string> {
};

struct ThingB : Entity<string, string> {
};

//Want to accept variations of Entity<...>::Inner,
//not Entity<...>::SomeOtherInner
template<typename I>
struct is_Entity_Inner {
    static const bool value
        = is_same<
            typename Entity<typename I::entity_args_t...>::Inner
            , I
        >::value
    ;
};

OUI?非?

1 个答案:

答案 0 :(得分:2)

定义:

template<typename ...> struct types;

然后:

template <typename... Args> struct Entity {

    struct Inner {
        typedef types<Args...> entity_args_t;
    };

    struct SomeOtherInner {
        typedef types<Args...> entity_args_t;
    };
};

然后,您可以将entity_args_t传递给具有types<T...>部分特化的模板。如果您输入Entity,则可以为Entity<T...>写一个部分专业化,这可能对您的案例更有意义

template <typename... Args> struct Entity {

    struct Inner {
        // Equivalent: typedef Entity entity_args_t;
        typedef Entity<Args...> entity_args_t;
    };

    struct SomeOtherInner {
        typedef Entity<Args...> entity_args_t;
    };
};

因此entity_args_t的typedef等于Entity<Args...>,你可以写如下(未经测试,但应该有效):

template<typename ProbablyInner, typename ProbablyEntity>
struct is_inner_impl : std::false_type 
{ };

template<typename ProbablyInner, typename ...Args>
struct is_inner_impl<ProbablyInner, Entity<Args...>> 
  : std::is_same<
      typename Entity<Args...>::Inner
      ProbablyInner>
{ };

template<typename ProbablyInner, typename = std::true_type>
struct is_inner : std::false_type 
{ };

template<typename ProbablyInner>
struct is_inner<ProbablyInner, 
  std::integral_constant<bool, is_inner_impl<
    ProbablyInner, 
    typename ProbablyInner::entity_args_t>::value>>
  : std::true_type 
{ };