2013-07-14 1 views
6

はSTDの変換機能が含まれている次のクラスを考えてみましょう:: string型:std :: stringで変換関数を使用できないのはなぜですか?

class SomeType 
{ 
    public: 

    SomeType(char *value) 
    { 
     _str = value; 
    } 

    operator std::string() 
    { 
     return std::string(_str); 
    } 

    private: 
    char *_str; 
}; 

は、次のコードはエラーでコンパイルに失敗:なし演算子「==」は

int main(int argc, char* argv[]) 
{ 
    SomeType a("test"); 

    if (a == std::string("test")) // ERROR on this line 
    { 
     int debug = 1; 
    } 

    return 0; 
} 
これらのオペランドと一致しません

私はstd :: stringオペランドを受け入れる演算子==メソッドを定義することができましたが、なぜ変換関数は機能しませんか?

+0

エラーは何ですか? –

+1

@Aniketエラーは問題です。 –

+0

これらの回答が参考になった場合は、受け付けてください。 – Borgleader

答えて

8

問題は、std :: stringは実際にはテンプレートであり、そのように私は比較演算子もテンプレートであると想像しています。そしてその場合、必要な引数に対して暗黙の変換が行われないということを思い出しています。つまり、呼び出すためにSomeTypeを文字列にキャストしなければならないということです。

効果的なC++の項目46に記載されているように:

[...], because implicit type conversions are never considered during template argument deduction. Never. Such conversions are used during function calls, yes, but before you can call a function, you have to know which functions exist. [...]

あなたはより多くの情報hereを見つけることができます。

+0

偉大な答え、洞察力に感謝します。 – Julius

4

std::stringはちょうどstd::stringそれはテンプレート1

template<...> 
bool operator (basic_string<...>& a, basic_string<...>& b) { 
    // 
} 

ですが、テンプレートの種類は、ここで推定することはできません実際のtypedefがありstd::basic_string<char, i_do_not_remember>

取得なしoperator ==にあります。

if (static_cast<std::string>(a) == std::string("test")) 
関連する問題