誰かがキャストのルールを説明できますか、そして変換があいまいな場合は?MSVC ++(Visual Studio 2010)とgcc-4.3.4で異なる答えを与える次のケースに少し混乱しています。
#include <string>
class myStr
{
std::string value;
public:
myStr(const char* val) : value(val) {}
operator const char*() const {return value.c_str();}
operator const std::string() const {return value;}
};
myStr byVal();
myStr& byRef();
const myStr& byConstRef();
int main(int, char**)
{
myStr foo("hello");
std::string test;
// All below conversions fail "ambiguous overload for 'operator='" in gcc
// Only the indicated coversions fail for MSVC++
test = foo; // MSVC++ error "'operator =' is ambiguous"
test = static_cast<std::string>(foo);
test = byVal(); // MSVC++ error "'operator =' is ambiguous"
test = static_cast<std::string>(byVal()); // MSVC++ error
// "'static_cast' : cannot convert from 'myStr' to 'std::string'"
test = byRef(); // MSVC++ error "'operator =' is ambiguous"
test = static_cast<std::string>(byRef());
test = byConstRef(); // MSVC++ error "'operator =' is ambiguous"
test = static_cast<std::string>(byConstRef());
return 0;
}
これらの変換のどれが合法であるかを管理するルールは何ですか?そして、との両方へmyStr
のキャストを定義するようなクラスを明確に使用するための準拠した方法はありますか?const char*
const std::string