我必须将您的代码发给您,因为我无法理解为什么会收到此错误! 我知道我可以使用模板..
class Mappable {
typedef boost::variant<int, bool, unsigned short, float, char, timeval,
double, std::string, size_t> MultiType;
private:
class Handler {
friend class Mappable;
public:
template<typename T>
operator T&() {
T t = 0;
try {
t = boost::get<T>(it);
} catch (...) {
}
return t;
}
template<class T>
Handler& operator=(const T& rhs) {
it = rhs;
return *this;
}
private:
Handler(MultiType& it, const std::string& key);
MultiType& it;
};
public:
Mappable(const std::string& tableName);
virtual ~Mappable();
Handler operator[](const std::string& key) {
return Handler(map_[key], key);
}
std::string keyTypeToString(const std::string& key) {
std::stringstream ss;
ss << boost::get<T>(map_[key]);
return ss.str();
}
private:
typedef std::map<std::string, MultiType> MultiTypeMap;
std::string valueFromKey(const MultiTypeMap::iterator& it);
template<class T>
MultiTypeMap map_;
};
/* Main.cpp */
int main() {
Mappable m;
m["x"] = 2;
m["data"] = "my data string value"; /* Correctly works */
cout << (int)(m["x"]); /* Correctly works */
cout << (string)(m["data"]); /* Error */
cout << m.keyTypeToString<string>("data"); /* Correctly works */
}
错误是:
../src/data/Mappable.h:98:41: error: call of overloaded ‘basic_string(Mappable::Handler)’ is ambiguous
../src/data/Mappable.h:98:41: note: candidates are:
/usr/include/c++/4.6/bits/basic_string.tcc:214:5: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
/usr/include/c++/4.6/bits/basic_string.tcc:171:5: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>, std::basic_string<_CharT, _Traits, _Alloc> = std::basic_string<char>]
/usr/include/c++/4.6/bits/basic_string.tcc:179:5: note: std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
我无法理解模棱两可的地方!
答案 0 :(得分:4)
您有任何类型的隐式转换。
template<typename T> operator T&();
这意味着,basic_string的任何单参数隐式构造函数都是可行的(char const *,std :: string等。)
咒语是: 隐含转换是邪恶的 。
在C ++ 11中,您可以将explicit
关键字添加到转化中。这意味着您将明确地调用static_cast<>
template<typename T>
explicit operator T&() { // throws on type mismatch
return boost::get<T>(it);
}