タグのように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>
ヘッダにパッチを適用することです上記のクラスに示されている点火演算子。しかし、これは、システムヘッダーのパッチを当てることと、その手順と結果はコンパイラーのバージョンに依存することを意味します(また、各インストールとコンパイラーのバージョンで繰り返さなければなりません)。
あなたの質問にもう少しコンテキストを追加し、上記のコンパイラの警告/エラーを各例に含めます。 – Nepho