C++の文法がわかりません visual studioのSTLから抜粋します 分からない部分を/////で上下挟みます template <class _Ty, _Ty _Val>
C++の文法がわかりません visual studioのSTLから抜粋します 分からない部分を/////で上下挟みます template <class _Ty, _Ty _Val> struct integral_constant { static constexpr _Ty value = _Val; using value_type = _Ty; using type = integral_constant; /////////////////////////// constexpr operator value_type() const noexcept{ /////////////////////////// return value; } _NODISCARD constexpr value_type operator()() const noexcept{ return value; } このoperatorが何をしているかわかりません 型 operator演算子(引数){} が私の理解しているoperatorの使い方です operator型(){} 戻り値は何でどういう演算をしますか?
回答をいただいてなんとなくわかりましたが 今回のこのテンプレートでの キャスト演算のオーバーロードは何をしたいのかがわかりません using value_type = _Ty; static constexpr _Ty value = _Val; なら constexpr operator value_type() const noexcept{ return value; } このtemplateの型の変数を返しているだけじゃないですか? stringをintにキャストするとかならわかりますが 何のためにやるのでしょうか?
C言語関連・106閲覧
ベストアンサー
『operator型(){}戻り値は何でどういう演算をしますか?』 戻り値は { } 内にある return 文で決定されます。 演算はその型への変換です。 ~例~ #include <string> struct sample { std::string s; operator int() const { return std::stoi(s); } }; #include <iostream> int main() { std::cout << sample{ "12345" } + 1 << '\n'; } 【戻り値】 std::stoi(s) の戻り値が返されます。 【演算】 sample 型オブジェクトを int 型に変換する演算を規定します。sample 型オブジェクトを int 型として扱うことが期待される場面で呼び出されます。 main 関数では 1 を足してみました。1 は int 型であり、従って sample{"12345"} は可能であれば int 型になって欲しいところです。そこで sample 型には operator int() があるのでそれを使おうという判断になります。
質問者からのお礼コメント
理解できました ありがとうございました
お礼日時:5/22 6:48