为什么编译器不执行类型转换? [英] Why doesn't the compiler perform a type conversion?

查看:163
本文介绍了为什么编译器不执行类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码。

#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 ++上编译。由编译器给出的错误报告不匹配运算符'<'in's< x'。问题是为什么编译器不是简单地根据给定的 SimpleStruct x 转换为 string > operator string()然后使用 operator< (string,string)

This code does not compile either on g++ or Microsoft Visual C++. The error report given by compilers is no match for operator '<' in 's < x'. The question is why does the compiler not simply convert the SimpleStruct x to string according to the given operator string () and then use operator < ( string, string )?

推荐答案

$ c> for std :: string 是一个函数模板。重载是:

operator< for std::string is a function template. The overloads are:

  template<class charT, class traits, class Allocator>
    bool operator< (const basic_string<charT,traits,Allocator>& lhs,
            const basic_string<charT,traits,Allocator>& rhs);
  template<class charT, class traits, class Allocator>
    bool operator< (const basic_string<charT,traits,Allocator>& lhs,
            const charT* rhs);
  template<class charT, class traits, class Allocator>
    bool operator< (const charT* lhs,
            const basic_string<charT,traits,Allocator>& rhs);

您的通话与任何可用的重载不匹配,因此它们都从列表中删除候选人。由于没有选择函数模板作为解析调用的候选项,因此没有将SimpleStruct转换为。

Your call doesn't match any of the available overloads, so they are all removed from a list of candidates. Since no function template was picked as a candidate for resolving the call, there is nothing to convert SimpleStruct to.

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
}

这篇关于为什么编译器不执行类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆