Eine benannte Operator Bibliothek:
namespace named_operator {
template<class D>struct make_operator{
constexpr make_operator(){}
};
template<class T, char, class O> struct half_apply { T&& lhs; };
template<class Lhs, class Op>
constexpr
half_apply<Lhs, '*', Op>
operator*(Lhs&& lhs, make_operator<Op>) {
return {std::forward<Lhs>(lhs)};
}
template<class Lhs, class Op, class Rhs>
constexpr auto
times(Lhs&& lhs, Op, Rhs&& rhs, ...) // ... keeps this the worst option
-> decltype(invoke(std::declval<Lhs>(), Op{}, std::declval<Rhs>()))
{
// pure ADL call, usually based off the type Op:
return invoke(std::forward<Lhs>(lhs), Op{}, std::forward<Rhs>(rhs) );
}
template<class Lhs, class Op, class Rhs>
constexpr auto
operator*(half_apply<Lhs, '*', Op>&& lhs, Rhs&& rhs)
-> decltype(
times(std::declval<Lhs>(), Op{}, std::declval<Rhs>())
)
{
return times(std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs));
}
}
Es unterstützt nur operator*
, aber erweitern sollte es offensichtlich sein. Kommissionierung Namen für times
Äquivalente ist ein bisschen ein Problem.
@ Anton-Lösung, mit einem benannten Betreiber ergänzt:
namespace power {
template<typename T>
constexpr T sqr(T a) {
return a * a;
}
template<typename T>
constexpr T power(T a, std::size_t n) {
return n == 0 ? 1 : sqr(power(a, n/2)) * (n % 2 == 0 ? 1 : a);
}
namespace details {
struct pow_tag {};
constexpr named_operator::make_operator<pow_tag> pow;
template<class Scalar>
constexpr Scalar times(Scalar lhs, pow_tag, std::size_t rhs) {
return power(std::forward<Scalar>(lhs), rhs);
}
}
using details::pow;
}
und jetzt dies funktioniert:
using power::pow;
int array[ 2 *pow* 10 ] = {0};
live example.
Wenn es nur eine Potenz von zwei ist, verwenden Sie '1 << DIM'. Ansonsten, nein. – Zeta
für Potenzen von zwei ... '1 << DIM': p – melak47
Es ist nicht unbedingt eine Potenz von 2 ;-) – Michael