2017-11-27 13 views
0

std :: string(std :: basic_string)に 'char'型の代入演算子があります。 しかし、このため、std :: stringは整数型を割り当てることができます。 少しの例を見てください。文字列への整数の割り当てを無効にする

#include <string> 
enum MyEnum{ Va = 0, Vb = 2, Vc = 4 }; 

int main(){ 
     std::string s; 
     s = 'a'; // (1) OK - logical. 
     s = Vc; // (2) Ops. Compiled without any warnings. 
     s = true; // (3) Ops.... 
     s = 23; // (4) Ops... 
} 

Q:どのように無効にする(または警告を追加します)(2、3、4)の状況?

There is a related Question

+0

あなたの質問にもう少しコンテキストを追加し、上記のコンパイラの警告/エラーを各例に含めます。 – Nepho

答えて

0

タグのようにC++ 03とGCC 4.8の制約を考えると、私は-Wconversionが有用何もすることができませんでした(とGCC 7で、それも私のために警告を生成しません。私は--std=c++03を使っていると言っているにもかかわらず)。

プロキシあなたの文字列をラップし、それがcharから割り当てることができますが、intから、それを禁止クラスオブジェクト経由割付:

このよう

は、あなたの呼び出し元のサイトでのみ最小限の変更を必要とする優れた実用的な解決策があります最終的な目標は、具体的警告やエラーを取得するためにのstd ::文字列を使用している場合であれば

#include <string> 
enum MyEnum{ Va = 0, Vb = 2, Vc = 4 }; 

struct string_wr { 
    string_wr (std::string& s) : val(s) {} 
    operator std::string&() const { return val; } 
    // we explicitly allow assigning chars. 
    string_wr& operator= (char) { return *this; } 

    // ww explicitly disable assigning ints by making the operator unreachable. 
    private: 
    string_wr& operator= (int); 

    private: 
    std::string& val; 
}; 


int main(){ 
     std::string s; 
     s = 'a'; // (1) OK - logical. 
     s = Vc; // (2) Ops. Compiled without any warnings. 
     s = true; // (3) Ops.... 
     s = 23; // (4) Ops... 

     string_wr m(s); // this is the only real change at the calling site 
     m = 'a'; // (1) OK - logical. 
     m = Vc; // (2) Should fail with "assignment is private" kind of error. 
     m = true; // (3) Should fail... 
     m = 23; // (4) Should fail... 

} 

しかし、C++ 03で、あなたの最良のオプションは、民間のint-尻を追加する<string>ヘッダにパッチを適用することです上記のクラスに示されている点火演算子。しかし、これは、システムヘッダーのパッチを当てることと、その手順と結果はコンパイラーのバージョンに依存することを意味します(また、各インストールとコンパイラーのバージョンで繰り返さなければなりません)。

関連する問題