2015-12-01 72 views
1

我對模板的大型家庭作業,並且它的部分是創建一個結構template <typename... Types> struct Foo,其中包含(公共type定義)公共結構template<typename Type> struct Bar其股份結構中,我們必須包括如果一個類型在參數給出FooBar0否則,其輸出1的公共方法template<typename Type> static constexpr size_t count();。示例(下面的代碼應編譯):添加模板特在可變參數模板給出各類

using FooBar = Foo<foo1,foo2,foo3>; 

using Foo1Type = FooBar::Bar<foo1>::type; 
// foo1 was given as argument to Foo and Bar 
static_assert(Foo1Type::count<foo1>() == 1); 
// foo2 was given as argument to Foo, but not Bar 
static_assert(Foo1Type::count<foo2>() == 0); 

using Foo4Type = FooBar::Bar<foo4>::type; 
// foo4 was not given as argument to Foo 
static_assert(Foo4Type::count<foo4>() == 0); 
static_assert(Foo4Type::count<foo1>() == 0); 

它看起來很硬派給我(我是新來的模板,剛開始讀abount他們),這似乎是我們必須通過可變參數模板參數迭代,以Foo,和迭代過程中莫名其妙的內部結構Bar創造新的專業化......我從來沒有見過這樣的事,所以我只能猜測它是如何完成的。

所以,我在一個很好的方式思考這個問題,或者我應該接近它以某種方式有什麼不同?我會很感激任何幫助(不只是完整的解決方案) - 任何有用的鏈接都歡迎。

+0

你允許哪一個C++標準版使用? 'constexpr'表示C++ 11或更高版本。 – melak47

+0

@ melak47的C++代碼是指最新的C++標準。 – edmz

+0

我甚至可以用C++ 17是我想 – qiubit

回答

1

據我瞭解,你內心的函數就是這樣的:

return contain<Type, TBar>{} && contain<Type, TFoos...>{}; 

這結構包含可寫的:

template <typename T, typename ... Ts> struct contain; 

// Partial specializations 
// Empty case 
template <typename T> struct contain<T> : std::false_type {}; 

// Found 
template <typename T, typename ... Tail> 
struct contain<T, T, Tail...> : std::true_type {}; 

// Not found, iterate the list 
template <typename T, typename Head, typename ... Tail> 
struct contain<T, Head, Tail...> : contain<T, Tail...> {}; 

Demo