Reputation: 1261
In the following sample code, I want to use the MACRO_EXPANSION
with variable arguments and {...}
to construct a list of EnumTypes
Objects. However, I cannot make this idea work. (PS. the code structure may seem not well, but I need it :))
#include <iostream>
#include <utility>
#include <initializer_list>
enum class EnumOneTypes {
One0,
One1
};
enum class EnumTwoTypes {
Two0,
Two1
};
struct EnumTypes {
EnumOneTypes one;
EnumTwoTypes two;
};
void do_something(std::initializer_list<EnumTypes> il) {
std::cout << "Do something" << std::endl;
}
// Need this struct to forward arguments
struct Register {
template <typename... TArgs>
Register(TArgs&&... args) {
do_something(std::forward<TArgs>(args)...);
//also do other things after do_something, omit here
// ...
}
};
// Use this macro to define global static objects
#define MACRO_EXPANSION(name, ...) \
static struct Register name(__VA_ARGS__)
MACRO_EXPANSION(
register_two,
{EnumOneTypes::One0, EnumTwoTypes::Two0},
{EnumOneTypes::One1, EnumTwoTypes::Two1}
);
MACRO_EXPANSION(
register_three,
{EnumOneTypes::One0, EnumTwoTypes::Two0},
{EnumOneTypes::One1, EnumTwoTypes::Two1},
{EnumOneTypes::One0, EnumTwoTypes::Two1}
);
int main() {
std::cout << "Test the usage of this macro" << std::endl;
return 0;
}
Upvotes: 3
Views: 957
Reputation: 2152
std::initializer_list
. So let's wrap the variadic arguments with braces.struct Register {
template <typename... TArgs>
Register(TArgs&&... args) {
do_something({std::forward<TArgs>(args)...}); // Make params to be initializer List
//also do other things after do_something, omit here
// ...
}
};
Register
constructor is templated, it seems like the compiler cannot deduce which type {EnumOneTypes::One0, EnumTwoTypes::Two0}
is of. So let's specify its type like:MACRO_EXPANSION(
register_two,
EnumTypes{EnumOneTypes::One0, EnumTwoTypes::Two0},
EnumTypes{EnumOneTypes::One1, EnumTwoTypes::Two1}
);
After applying these two, it compiles successfully and runs with output:
Do something
Do something
Test the usage of this macro
I tested in godbolt.
Upvotes: 2