c++ - 循环 typedef 列表

标签 c++ arrays metaprogramming typedef

如果标题有点误导,我很抱歉。

我有一个循环一些数据的函数。每次迭代都会更改此数据的类型。

基本上我有这样的东西:

for(int i = 0; i < limit; i++)
{
  type object;
  object.do_stuff();
}

例如,在第一次迭代中,“type”将是 int,在第二次迭代中,“type”将是 double,等等。

我不能使用 varyadic 模板,因为我有超过 100 个元素,据我所知,这对系统来说会非常费力。

我的想法是创建一个“typedef vector ”来循环对象的所有类型。

vector<????> type;
type.push_back(int);
type.push_back(double);
...
for(int i = 0; i < limit; i++)
{
  type[i] object;
  object.do_stuff();
}

我不知道这是否有可能。

我看到了类型列表的基础知识,但我不知道是否可以重现循环。

最佳答案

I can't use varyadic templates because i have more than 100 elements and from what i know it will be very taxing for the system.

您所知道的不是过时的就是不准确的。看看metaben.ch了解在最小的编译时间影响下可以得到多大的类型列表。


My idea was to create a "vector of typedefs" to cycle all the types of the objects.

那是一个类型列表。您可以执行以下操作:

// Store the type in a value for convenience
template <typename T>
struct type_wrapper
{
    using type = T;
};

template <typename... Ts>
struct typelist
{
    template <typename F>
    constexpr void for_each(F&& f)
    {
        // C++17 fold expression over comma operator
        (f(type_wrapper<Ts>{}), ...);
    }
};

C++17 用法:

typelist<int, float, char>{}.for_each([](auto t)
{
    using type = typename decltype(t)::type;
    // Use `type`
});

C++20 用法(对 typelist 进行了细微更改):

template <typename... Ts>
struct typelist
{
    template <typename F>
    constexpr void for_each(F&& f)
    {
        // C++17 fold expression over comma operator
        (f.template operator()<Ts>(), ...);
    }
};

typelist<int, float, char>{}.for_each([]<typename T>()
{
    // Use `T`
});

我写了一篇与这个主题相关的短文:"compile-time iteration with C++20 lambdas " .

关于c++ - 循环 typedef 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51246727/

相关文章:

ruby-on-rails - 在 Active Record 类中定义类方法

c++ - Blitz 在 vs 2013 中不起作用

c++ - 在 OSX 上从源构建 GIMP 2.10 在 "gimp-debug-tool-2.0"上失败

java - 从java中的数组中删除特定索引

ruby - 比较字符串并打印出匹配项 (Ruby)

r - 如何将集合运算表达式编程为函数的参数?

c++ - 如何有效地将 vector 与 C++ 进行比较?

c++ - 在c++中应该使用什么代码代替getche

Java 根据列日期对 csv 文件进行排序

ruby - 如何将 lambda 绑定(bind)到 Ruby 中的散列?