微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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
}

原文地址:https://www.jb51.cc/c/113594.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐