2015-12-01 69 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