加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:50:06 所属栏目:百科 来源:网络整理
导读:请考虑以下代码. #include iostream#include stringstruct 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. b
请考虑以下代码.
#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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读