如果标题有点误导,我很抱歉。
我有一个循环一些数据的函数。每次迭代都会更改此数据的类型。
基本上我有这样的东西:
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/