gpt4 book ai didi

c++ - 为类模板忽略了用户定义的转换运算符(对于非模板则不然)

转载 作者:太空狗 更新时间:2023-10-29 20:20:25 28 4
gpt4 key购买 nike

此代码确实可以编译(重要的一点是 F() 只接受 A s,并且由于存在从 BA 的隐式转换,我可以轻松地将 B 传递给它。 )

struct A {};

struct B {
constexpr operator A () const {return {};}
};

void F (A a) {}

int main() {
F(B());
return 0;
}

但是模板化版本不编译:

template <typename T>
struct A {};

template <typename T>
struct B {
constexpr operator A<T> () const {return {};}
};

template <typename T>
void F (A<T> a) {}

int main() {
F(B<int>());
return 0;
}

在 GCC 上出现以下错误(以及在 MSVC 上的等效错误):

error: no matching function for call to ‘F(B<int>)’

(附加信息表明有一个 F(A<>)B 不继承自 A。)

作为记录,在 A 中实现隐式转换运算符也没有帮助。

为什么模板版本无法编译?我错过了什么吗?或者实际上没有办法用类模板来做?!

(注意:我知道我可以在调用站点明确地将 B 转换为 A;这不是我喜欢的。)

最佳答案

Template argument deduction不考虑隐式转换。

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

模板参数T必须首先推导(在重载决议之前),但给定参数 A<T>带参数 B<int> , T不能从中推导出来;然后编译失败。

作为解决方法,您可以像您所说的那样使用显式转换,或者显式指定模板参数。

F<int>(B<int>());

关于c++ - 为类模板忽略了用户定义的转换运算符(对于非模板则不然),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51380485/

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