以下のテストコードにて、value_の値を受け取るためにはcast()を使用しなければならないとします。
値を受け取るのに毎回関数名を記述するのは面倒なので演算子のオーバーロードの使用すればもっと扱いやすくなると考えたのですが、この記述では2つともコンパイルエラーとなってしまいました。
ただ単に記述の仕方が間違っているのか、それともこういった技術自体が不可能なのか、お教えください。
Cpp
1#include <iostream> 2 3template <class T> 4class test 5{ 6 T value_; 7public: 8 test(const T& value) 9 : value_(value) {} 10 11 T& operator =(const T& value) 12 { 13 value_ = value; 14 return *this; 15 } 16 17 template <class U> 18 U cast() const 19 { 20 return static_cast<U>(value_); 21 } 22 23 // こ↑こ↓ 24 // 関数オブジェクトによるもの 25 template <class U> 26 U operator()() const 27 { 28 return this->cast<U>(value_); 29 } 30 // 型変換演算子によるもの 31 template <class U> 32 operator U const 33 { 34 return this->cast<U>(value_); 35 } 36}; 37 38int main() { 39 using namespace std; 40 test t = 3.14; 41 42 cout << t.cast<int>() << endl; // OK 43 cout << t<int>() << endl; // NG 44 cout << (int)t << endl; // NG 45 46 return 0; 47}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/25 14:36 編集
2019/06/25 14:35