Given a list of types, names, and default values, I could easily write a tool that generates valid c++ code that declares a class with a member variable of each type, name and default value. For example, given the list
- int, foo, 42
- float, bar, 0.1f
(and class name "Baz"), it would generate
class Baz {
int foo = 42;
float bar = 0.1f;
}
If a tool could generate such a class, couldn't the compiler do it for me? I'm thinking about something along these lines (note: this is pseudocode):
template <typename ...MemberTypes> class Baz {
MemberTypes::type... MemberTypes::name... = MemberTypes::default...;
}
Above class would be created something like
using MyBaz = Baz<member_type<int, "foo", 42>, member_type<float, "bar", 0.1f>>;
Reasons why this might be possible:
- All required information is available at compile time. An external tool can easily do it.
- It is possible to create a class with a tuple instead of dedicated member variables in a similar fashion (Declare member variables from variadic template parameter).
- I can approximate this for finite combinations of members using template specializations.
- Template metaprogramming is turing-complete (C++ templates Turing-complete?), so "everything" should be possible.
Reasons why it might be impossible:
- Template parameters can not be string literals (Passing a string literal as a parameter to a C++ template class), or, indeed, anything but integers.
- I can't think of a way of doing this (weak argument).
If this is possible, how would it be done? If it isn't possible, why not? Does the upcoming c++17 change anything in this respect?
Update: Example Problem:
Often, configuration data is stored as hierarchy of strings or some other form of "any type". This, however, leads to ugly code (config.get<int>("core.timeout")
) and prevents the compiler from helping out with, for example, typos (config.get<int>("core.timeuot")
).
By declaring every configuration variable with its true type, the compiler can check types and prevent spelling-errors. However, then there needs to be custom code to read configuration data into the right member variables. If new configuration switches are added, it is easy to forget updating this code.
It would be convenient to just specify the types and names of all members, and then let the compiler auto-generate the class (including a method to read a config file). This is a possible use-case for the functionality I asked for.
std::tuple<typename MemberTypes::type...> all_members = {MemberTypes::default...};
– Chancerystd::tuple
is not a viable substitute? – Elecampanemember_type<float, "bar", 0.1f>
".float
template arguments are not supported by c++. See here for a list of allowed non-type template parameter types. – Bellini