2

私は初心者の C++ 開発者で、テンプレートを介したオペレーターの統合について質問がtoStringあります。ostream私はそのようなコードを持っています:

    struct MethodCheckerTypes{
        typedef unsigned char TrueType;
        typedef long FalseType;
    };
    template<typename T>struct HasToString{
        template<typename K>static typename MethodCheckerTypes::TrueType test(decltype(&K::toString));
        template<typename> static typename MethodCheckerTypes::FalseType test(...);
        static const bool value = sizeof(test<T>(0)) == sizeof(typename MethodCheckerTypes::TrueType);
        typedef decltype(test<T>(0)) ValueType;
    };

    template<typename T, typename K> struct IfDef{};
    template<> struct IfDef<typename MethodCheckerTypes::TrueType, ostream&>{
        typedef ostream& type;
    };

    class WithToString{
    public:
        string toString() const{
            return "hello";
        }
    };

    template<typename F, typename CharT, typename Traits> typename IfDef<typename HasToString<F>::ValueType, basic_ostream<CharT, Traits>&>::type operator<<(basic_ostream<CharT, Traits>& out, const F &ref){
        out<<ref.toString().c_str();
        return out;
    }
int main(int argc, char **argv){
    WithToString hasToString;
    cout<<hasToString<<endl;
    return 0;
}

コードはエラーなしでコンパイルされ、アプリケーションは正常に実行されました。そのようなアプローチを使用するのは良いことですか?ブーストの助けを借りずに実装したかったのです。

4

2 に答える 2

1

単独で実装するアプローチoperator<<は正常です。しかし、あなたが理解していない言語の部分を使用することは悪い習慣です(私は初心者がそのようなコードを書くことができるとは思いません)。2つの選択肢があります:toStringメンバー関数を実装するか、オーバーロードしoperator<<(std::ostream&, T)ます。後者のアプローチではboost::lexical_cast、オブジェクトを文字列に変換するために使用できます。私の場合、後者のアプローチはよりC ++っぽいので、メンバー関数なしで何かを実行できる場合は、そうする方がよいでしょう。

于 2011-04-29T11:36:35.627 に答える