一個名爲operator庫:
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));
}
}
它只支持operator*
,但擴展它應該是顯而易見的。採用times
當量的名字是有點問題。
@安東的解決方案,一個叫運營商增強:
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;
}
,現在這個工程:
using power::pow;
int array[ 2 *pow* 10 ] = {0};
live example。
如果它只是2的冪,則使用'1 << DIM'。否則,不。 – Zeta 2014-12-03 11:27:46
對於兩個功能......'1 << DIM':p – melak47 2014-12-03 11:27:49
它不一定是2的冪;-) – Michael 2014-12-03 11:30:57