gpt4 book ai didi

c++ - 如何使用模板函数进行隐式转换

转载 作者:行者123 更新时间:2023-12-02 17:18:41 24 4
gpt4 key购买 nike

非常简化示例(不管类A和运算符在做什么,这只是示例):

#include <iostream>
using namespace std;

template <bool is_signed>
class A {
public:
// implicit conversion from int
A(int a) : a_{is_signed ? -a : a}
{}

int a_;
};

bool operator==(A<true> lhs, A<true> rhs) {
return lhs.a_ == rhs.a_;
}

bool operator==(A<false> lhs, A<false> rhs) {
return lhs.a_ == rhs.a_;
}

int main() {
A<true> a1{123};
A<false> a2{123};

cout << (a1 == 123) << endl;
cout << (a2 == 123) << endl;

return 0;
}

这有效。

但是如果我用模板替换两个 operator==(具有相同的主体):

template <bool is_signed>
bool operator==(A<is_signed> lhs, A<is_signed> rhs) {
return lhs.a_ == rhs.a_;
}

,其编译产生错误:

prog.cpp: In function ‘int main()’:
prog.cpp:31:14: error: no match for ‘operator==’ (operand types are ‘A<true>’ and ‘int’)
cout << (a1 == 123) << endl;
~~~^~~~~~
prog.cpp:23:6: note: candidate: ‘template<bool is_signed> bool operator==(A<is_signed>, A<is_signed>)’
bool operator==(A<is_signed> lhs, A<is_signed> rhs) {
^~~~~~~~
prog.cpp:23:6: note: template argument deduction/substitution failed:
prog.cpp:31:17: note: mismatched types ‘A<is_signed>’ and ‘int’
cout << (a1 == 123) << endl;
^~~

这里可以使用模板吗?我可以以某种方式使用 C++17 用户定义的模板推导指南吗?还是其他什么?

最佳答案

template argument deduction 中不考虑隐式转换,这会导致扣除 is_signed第二个函数参数失败。

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

如果您始终使用operator==风格如 a1 == 123 ,即 A<is_signed>始终用作第一个操作数,您可以从推导中排除第二个函数参数。例如

template <bool is_signed>
bool operator==(A<is_signed> lhs, std::type_identity_t<A<is_signed>> rhs) {
return lhs.a_ == rhs.a_;
}

LIVE

PS: std::type_identity 从 C++20 开始支持;即使实现起来并不难。

关于c++ - 如何使用模板函数进行隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58508084/

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