Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a specialized struct template without providing the chevron info?

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 !

like image 513
lucas_v67 Avatar asked Sep 16 '25 22:09

lucas_v67


1 Answers

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...);
}
like image 160
Evg Avatar answered Sep 19 '25 10:09

Evg