C++ Preprocessor: Iterate over comma-separated list argument

Viewed 99

I'm trying to generate comma-separated list of vectors of given types to instantiate std::variant of vectors. (I didn't want to write a huge one-line code so I decided to use macros. I am open to new suggestions for this root problem).

Is it possible to write macro which would define a preprocessor variable which would appear to be a list of comma-separated vectors of given types:

#define INTEGRAL_TYPES char, int, long long, size_t
#define MAGIC_MACRO(x) ???

#define SEQUENTIAL_TYPES MAGIC_MACRO(INTEGRAL_TYPES) // this will generate std::vector<char>, std::vector<int>, std::vector<long long>, std::vector<size_t>
1 Answers

This can be done with C++ templates:

#include <variant>
#include <vector>

template<typename... Types>
using VariantVectorGenerator = std::variant<std::vector<Types>...>;

using MyWeirdVariantVectorThing = VariantVectorGenerator<int, double, float>;

int main() {
    MyWeirdVariantVectorThing x;
    x = std::vector{42};
    x = std::vector{13.2};
}

In this case int, double, float could be moved into a macro. Not sure to which extend it is possible to simplify this.

Related