To be my question more clear, firstly I show you my templated struct State
to describe the state vector of a state space according to the dimension :
template<unsigned int Dimension>
struct State;
// Specialization : for dimension 1
template<>
struct State<1>
{
State() = default;
State(double x) : x{ x } {}
double x{};
};
// Specialization : for dimension 2
template<>
struct State<2>
{
State() = default;
State(double x, double dx) : x{ x }, dx{ dx } {}
double x{};
double dx{};
};
// Specialization : for dimension 3
template<>
struct State<3>
{
State() = default;
State(double x, double dx, double ddx) : x{ x }, dx{ dx }, ddx{ ddx } {}
double x{};
double dx{};
double ddx{};
};
By this way, I can build a state
variable with the 3 dimensions :
1 dimension : auto state = State<1>(2.0);
2 dimensions : auto state = State<2>(2.0, 4.7);
3 dimensions : auto state = State<3>(2.0, 4.7, 5.9);
But I am wondering :
Can I define the variable state without providing the dimension value in chevron, but only with the compile to deduce it from the number of value I provide in the constructor. Such as :
// What i would like to be able to do
auto state = State{2.0, 4.7}; // FAILED ( 2 values provided, so I would like the compilator to deduce it's the constructor of State<2> )
// Instead of doing
auto state = State<2>{2.0, 4.7};
Thanks you for your help !
Simply add a deduction guide:
template<class... Ts>
State(Ts...) -> State<sizeof...(Ts)>;
Demo
Before C++17, a typical solution was to introduce a helper function:
template<class... Ts>
State<sizeof...(Ts)> makeState(Ts... values) {
return State<sizeof...(Ts)>(values...);
}
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