C++关于类类型转换的一个问题?

#include <iostream>
using namespace std;

class A {
public:
    A(const string &str):str(str){}
    operator string() const { return str; }
    string str;
};

class B {
public:
    B(int i):i(i){}
    operator int() const { return i; }
    int i;
};

template<typename T>
int compare(const T &a, const T &b)
{
    if(a < b) return -1;
    if(b < a) return 1;
    return 0;
}

int main()
{
    A a1("a"),a2("b");
    B b1(10),b2(20);
    
    // 这里为什么不能调用 compare(a1,a2)
    // a1和a2应该都能转换成string,而且string也定义了 < 运算符
    //cout<<compare(a1,a2)<<endl;
    cout<<compare(b1,b2)<<endl;

    return 0;
}
阅读 1.3k
1 个回答

因为 std::stringoperrator< 是一个模板

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

模板参数推断是不考虑自定义转换的。当参数是 A 的时候,模板参数是推断不出来的。所以直接就失败了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题