c – 为什么编译器不执行类型转换?

请考虑以下代码.
#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
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...