I can't find a way to get this to work. Is it even possible? I don't see why it wouldn't be.
template <auto id, typename FirstField, typename... OtherFields>
struct FieldTypeById {
using Type = int;
};
template <auto id>
struct FieldTypeById<id, void> {
using Type = void;
};
int main()
{
using t1 = FieldTypeById<0, int>::Type;
using t2 = FieldTypeById<1>::Type;
return 0;
}
https://godbolt.org/z/AggnDq
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration.
Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.
A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.
The problem in your example isn't the specialization, it's fine. The problem is that FieldTypeById<1>
cannot deduce the type FirstField
is. You can amend that by simply adding a default to the primary template:
template <auto id, typename FirstField = void, typename... OtherFields>
struct FieldTypeById {
using Type = int;
};
Now all arguments are given explicitly, taken from defaults, or deduced (as an empty pack). After all the arguments are known, the specialization for those arguments can be used.
See it live
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With