2011-05-17 53 views
2

請原諒對C++類型演繹的無知,但我希望能夠在參數包的定義中攜帶,以便稍後我可以測試內部類型。這可能嗎?例如:推導參數包w/out顯式傳遞它作爲模板參數嗎?

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?非?

回答

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...>一個局部特殊化的模板。如果你的typedef的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等於Entity<Args...>一個typedef,你可以這樣寫如下(未經測試,但應工作):

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 
{ }; 
+0

因此,在'is_Entity_Inner'元函數,我反而有'is_same :: value'? – 2011-05-17 16:05:33

+0

@pheedbaq請參閱更新。 – 2011-05-17 16:11:16

+0

@pheedbaq臨界點是你訪問':: entity_args_t'的地方。如果你希望'is_inner'產生任意其他類型的'false',你必須在SFINAE上下文中訪問這個類型,這樣如果沒有成員叫做':: entity_args_t',那就沒有硬編譯時錯誤。 – 2011-05-17 16:25:18