Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for implicit conversion from double to std::array<double,1>?

I have a template class like this:

template<int dimension>
class Foo{
  Foo(std::array<double, dimension>);
}

and a function

func(Foo<1> f);

I would like to be able to call the function and the constructor like this:

func(1);
Foo<1> f(1);

instead of

func({1});
Foo<1> f({1});

Is there a nice way to achieve this?

If implicit conversion is not possible, can 1 add a constructor for the Foo<1> case only?

like image 902
QuantumZero Avatar asked Dec 05 '22 10:12

QuantumZero


1 Answers

An implicit conversion for a double into a std::array<double, 1> is not possible. That would require overloading a conversion operator for double but that can't be done as you can't overload operators for built in types.

What you can do is add

Foo(double);

constructor and then use a static_assert like

static_assert(dimension == 1, "single double constructor only works if dimension == 1");

in the body of the constructor to limit it to only work when the array has a size of 1. (I like using static_assert when I can because it lets you write a nice, descriptive, error message)


You should consider renaming dimension to size since that is what is specifying in the array.

like image 131
NathanOliver Avatar answered Feb 16 '23 02:02

NathanOliver