请考虑以下代码.
#include <iostream> #include <string> struct SimpleStruct { operator std::string () { return value; } std::string value; }; int main () { std::string s; // An empty string. SimpleStruct x; // x.value constructed as an empty string. bool less = s < x; // Error here. return 0; }
该代码不会在g或Microsoft Visual C上编译.编译器提供的错误报告与运算符’<'在' X'.问题是为什么编译器不会根据给定的操作符string()简单地将SimpleStruct x转换为字符串,然后使用operator< (string,string)?
解决方法
操作符LT;对于std :: string是一个函数模板.重载是:
template<class charT,class traits,class Allocator> bool operator< (const basic_string<charT,traits,Allocator>& lhs,const basic_string<charT,Allocator>& rhs); template<class charT,const charT* rhs); template<class charT,class Allocator> bool operator< (const charT* lhs,Allocator>& rhs);
您的呼叫与任何可用的超载不匹配,因此它们都从候选人列表中删除.由于没有选择功能模板作为解决调用的候选项,所以没有任何可以将SimpleStruct转换为.
template <class T> class String { }; template <class T> bool operator< (const String<T>&,const String<T>&) { return true; } //if a suitable non-template function is available,it can be picked //bool operator< (const String<char>&,const String<char>&) { return true; } struct SimpleStruct { operator String<char> () { return value; } String<char> value; }; int main() { String<char> s; SimpleStruct ss; s < ss; //the call doesn't match the function template,leaving only the commented-out candidate }