lundi 19 octobre 2020

Make template function constexpr depending on type

I have a template function:

template <typename T>
constexpr T Square(T t) {
  return t * t;
}

This works fine when doing:

constexpr int four_square = Square(4);

Unfortunately I also have a user defined arithmetic type, MyInt whose multiplication operator is not defined as constexpr because it is not a single line and the code needs to compile in C++11 as well. So clearly the following won't work:

constexpr MyInt four_square = Square(MyInt(4));

But I want to be able to write:

const MyInt four_square = Square(MyInt(4)); // Note, const not constexpr.

This code doesn't compile because MyInt doesn't support constexpr even though I am not utilizing the constexpr in my code.

Is there any way to write a template function that will return a constexpr for types that support constexpr, but will return a non-constexpr for types that don't.

What I want to avoid is duplicating the implementation of Square, so if I could write:

template <typename T>
constexpr T ConstSquare(T t) {
  return t * t;
}

template <typename T>
T Square(T t) {
  return ConstSquare(t);
}

That would be fine but I can't because I can't call ConstSquare<MyInt>.

Note The function Square is not really what my function does, so whereas repeating t * t doesn't sound so painful, in my case it is more annoying.

Aucun commentaire:

Enregistrer un commentaire