2017-10-20 18 views
5

を演算子オーバーロードでキックしていない次の例を考えてみましょう:暗黙の変換演算子は、

#include <string> 
#include <sstream> 

struct Location { 
    unsigned line; 

    template<typename CharT, typename Traits> 
    operator std::basic_string<CharT, Traits>() const { 
    std::basic_ostringstream<CharT, Traits> ss; 
    ss << line; 
    return ss.str(); 
    } 
}; 

int main() 
{ 
    using namespace std::string_literals; 

    Location loc{42}; 

    std::string s1 = "Line: "s.append(loc) + "\n"s; // fine 
    //std::string s2 = "Line: "s + loc + "\n"s; // error 
} 

コメント行は、コンパイルエラーが発生します。no match for 'operator+'。どうして?私の最初の考えは、operator std::stringを変換してからoperator+への呼び出しを実行することでした。これは.appendと同じ方法です。

暗黙の変換のレベルは1つのみであるため、実行する必要があります。

Live Demo

+0

ご迷惑をおかけして申し訳ありませんが、私は作業コードを取得するために表示されません。 's'とは何ですか? – gsamaras

+3

@gsamaras http://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s – Holt

+0

右@Holt、ありがとう! – gsamaras

答えて

2

あなたのオペレータは、このようにテンプレート引数を推定する必要がある、テンプレートです。コンパイラはbasic_string<_CharT, _Traits, _Alloc>Locationを一致させようとするので、それはできません。失敗します。

コードは実際にはそのポイントに到達しないので、問題はオーバーロードであり、変換ではありません。

変更この:これに

std::string s2 = "Line: "s + loc + "\n"s; 

std::string s2 = "Line: "s + std::string(loc) + "\n"s; 

し、コンパイラエラーをよく見ると、それは言及するので、あなたは、問題ないはずです。

template argument deduction/substitution failed: 
prog.cc:22:32: note: 'Location' is not derived from 'const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>' 
    std::string s2 = "Line: "s + loc + "\n"s; // error 
           ^~~ 

をその他の同様のメッセージです。

0

はstdへの明示的なキャスト:: stringが私の作品:https://godbolt.org/g/WZG78z

std::string s2 = "Line: "s + std::string(loc) + "\n"; // was error 
関連する問題