operator double()
足せばいいというのはまあそうといえばそうなのですが、explicitじゃない型変換演算子を定義するのも正直どうかと思うので代案です。CPOを作ってみます。
cpp
1#include <iostream>
2#include <cmath>
3#include <concepts>
4namespace foo {
5class CustomInt {
6public:
7 CustomInt(int rhs) : value(rhs) {}
8 explicit operator int() const noexcept { return value; };
9 template<std::integral T>
10 auto pow(T y) { return std::pow(this->value, y); }
11private:
12 int value;
13};
14std::ostream& operator<<(std::ostream& lhs, const CustomInt& rhs)
15{
16 lhs << static_cast<int>(rhs);
17 return lhs;
18}
19inline namespace cpo {
20 namespace detail{
21 template <class T, class U>
22 concept has_pow_1 = requires (T x, U y) {
23 std::integral<U>;
24 {x.pow(y)} -> std::floating_point;
25 };
26 template <class T, class U>
27 concept has_pow_2 = requires (T x, U y) {
28 std::floating_point<U>;
29 {x.pow(y)} -> std::same_as<U>;
30 };
31 }
32 template <class T, class U>
33 concept has_pow = detail::has_pow_1<T, U> || detail::has_pow_2<T, U>;
34 struct pow_t {
35 template<std::floating_point T>
36 T operator()(T x, T y) const { return std::pow(x, y); }
37 template<std::integral T1, std::integral T2>
38 auto operator()(T1 x, T2 y) const { return std::pow(x, y); }
39 template<class T, class U> requires has_pow<T, U>
40 auto operator()(T x, U y) const { return x.pow(y); }
41 };
42 inline constexpr pow_t pow{};
43}
44}
45int main() {
46 // 1
47 foo::CustomInt hoge = {0};
48 std::cout << hoge << std::endl;
49 hoge = 20;
50 std::cout << foo::pow(static_cast<int>(hoge), 2) << std::endl;
51
52 // 2
53 std::cout << foo::pow(hoge, 2) << std::endl;
54}
https://wandbox.org/permlink/mMZyvzq64bdhQogj
ref:
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/04/05 01:23