gpt4 book ai didi

c++ - 为可变参数模板中给定的所有类型添加模板特化

转载 作者:行者123 更新时间:2023-11-30 05:34:58 26 4
gpt4 key购买 nike

我在模板上有一个很大的家庭作业,其中一部分是创建一个结构 template <typename... Types> struct Foo , 其中包含一个公共(public)结构 template<typename Type> struct Bar共享(公开 type 定义)一个结构,我们必须在其中包含一个公共(public)方法 template<typename Type> static constexpr size_t count();输出 1如果在 Foo 的参数中给出了类型和 Bar0否则。示例(应编译以下代码):

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);

它对我来说看起来很硬核(我是模板的新手,刚开始阅读它们),似乎我们必须通过可变模板参数迭代到 Foo ,并在迭代期间以某种方式为内部结构创建新的特化 Bar ...我从未见过这样的事情,所以我只能猜测它是如何做到的。

那么,我是在以一种好的方式思考这个问题,还是应该以某种不同的方式来处理它?我将不胜感激任何帮助(不仅仅是完整的解决方案)- 欢迎任何有用的链接。

最佳答案

据我了解,您的内部函数类似于:

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

关于c++ - 为可变参数模板中给定的所有类型添加模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34027473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com