2017-05-28 40 views
6
template<typename T> struct S {}; 
template<typename T> struct R {}; 

int main() { 
    typedef S<double> s1; 
    typedef S<int> s2; 
    typedef R<int> s3; 
    static_assert(xxx<s1, s2>::value, 
       "No, assertion must not be raised"); 
    static_assert(xxx<s2, s3>::value, 
       "Yes, assertion must be raised"); 
} 

所以,我想xxx<s1, s2>::value返回true,而xxx<s2, s3>::value期間編譯時返回false。獲取原始結構/類名

在C++中,xxx的存在是不可能的嗎? 或者,C++在理論上是否存在xxx,但可能沒有人做過它?

+0

所以,'xxx :: value'是'true' iff'T'和'U'是同一個模板的特化版本嗎? – Quentin

+0

@Quentin:是的:) –

回答

5

用途使用模板模板參數兩個專業進行這種「匹配」:

template< 
    typename T, 
    typename V> 
struct xxx; 

template< 
template <class> class A, 
template <class> class B, 
typename X, 
typename Y> 
struct xxx<A<X>, B<Y>> { 
    static constexpr const int value = false; 
}; 


template< 
template <class> class U, 
typename X, 
typename Y> 
struct xxx<U<X>, U<Y>> { 
    static constexpr const int value = true; 
}; 

With your code on ideone

注:這是一個真正的類型特點,你不應該手動設置value,但來自std::integral_constantstd::true_typestd::false_type)。以上只是我在手機上做的快速樣機。

+0

什麼是* constexpr const *? –

+1

你是否需要_two_專業化? –

+0

@HWalters不,但是如果使用兩個專門化的類型,而不是某些模板的實例化,則會發生錯誤。我更喜歡這種方式,因爲現在這個特質只有一個*事物(相同的模板?)而不是兩個(模板?相同的模板?)。 –

1

喜歡的東西same_base_template

#include <type_traits> 
template<class A, class B> 
struct same_base_template : std::false_type{}; 

template<template<class...> class S, class... U, class... V> 
struct same_base_template<S<U...>, S<V...>> : std::true_type{}; 

編輯:

而第三專業化,因爲你使用非類型模板參數(std::ratio):

template<class T, template<T...> class S, T... U, T... V> 
struct same_base_template<S<U...>, S<V...>> : std::true_type{}; 

Demo

這使用true_typefalse_typetype_traits,所以我們不需要自己寫一個constexpr bool value。我在這裏使用了一個可變參數模板,因爲它稍微更通用一些,並且只需要幾個按鍵就可以完成。對於你的具體用例,你不需要它們)

+0

我所有的耳朵對一個更好的名字比'same_base_template'。 – AndyG

+0

當我使用'same_base_template'以下面的方式通過首先包括頭'ratio':'INT主(){的typedef的std ::比<7, 8> R1; typedef std :: ratio <12, 9> r2; static_assert(same_base_template :: value,「不,不應該引發斷言」); }',用'克編譯它++ -std = C++ 14 -o兆瓦mwe.cpp'提高了靜態斷言'錯誤:靜態斷言失敗:否,斷言不得raised',其不應當如此。任何想法? –

+0

@TadeusPrastowo:這是因爲'std :: ratio'正在接受非類型的模板參數(比例的整數值)。這與我的預期略有不同,所以我又增加了一項專業化。我更新了我的帖子。看到新的演示。 – AndyG