gpt4 book ai didi

c++ - 带转换运算符的模板参数

转载 作者:行者123 更新时间:2023-11-30 02:31:43 25 4
gpt4 key购买 nike

#include <iostream>

template <typename T1, typename T2>
bool func(const T1& t, const T2& t2) {
return t == t2;
}


class Base {
public:
bool operator ==(const Base&) const { return true;}
Base(int y) : x(y) {}
operator int() {
return x;
}
int x;
};

int main() {
func<long, Base>(4L, Base(5)); // not ok
func<long, long>(4L, Base(5)); //ok
}

有人可以详细说明为什么第一个版本不起作用吗?也就是说为什么func中的二元运算符==不使用转换运算符int将绑定(bind)到Base的模板参数转换成int?

是否可以仅通过修改类 Base 来使版本 1 工作?

最佳答案

您的 func 通过 const 引用接受其参数,但是在您的 Base 类中定义的 operator int() 是一个非常量成员功能。将其标记为 const 成员函数,如下所示,您的代码将通过编译:

#include <iostream>

template <typename T1, typename T2>
bool func(const T1& t, const T2& t2) {
return t == t2;
}


class Base {
public:
bool operator ==(const Base&) const { return true;}
Base(int y) : x(y) {}
operator int() const {
return x;
}
int x;
};

int main() {
func<long, Base>(4L, Base(5)); // ok now!
func<long, long>(4L, Base(5)); // ok
}

Live example

关于c++ - 带转换运算符的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37322576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com