gpt4 book ai didi

c++ - 重载转换运算符模板

转载 作者:IT老高 更新时间:2023-10-28 22:21:23 26 4
gpt4 key购买 nike

考虑以下简单示例

struct C
{
template <typename T> operator T () {return 0.5;}
operator int () {return 1;}
operator bool () {return false;}
};

int main ()
{
C c;
double x = c;
std::cout << x << std::endl;
}

使用 Clang 编译时,报如下错误

test.cpp:11:12: error: conversion from 'C' to 'double' is ambiguous
double x = c;
^ ~
test.cpp:4:5: note: candidate function
operator int () {return 1;}
^
test.cpp:5:5: note: candidate function
operator bool () {return false;}
^
test.cpp:3:27: note: candidate function [with T = double]
template <typename T> operator T () {return 0.5;}
^
1 error generated.

其他编译器会产生类似的错误,例如 GCC 和 Intel iclc

如果我删除 operator intoperator bool。它编译良好并按预期工作。如果只删除其中一个,即保留模板运算符并说 operator int,则始终选择非模板版本。

我的理解是,只有当模板和非模板重载函数在它们完全匹配或都需要相同的转换顺序的意义上相等时,才会首选非模板版本。但是在这种情况下,编译器似乎没有将运算符模板视为完美匹配。而当 boolint 重载都存在时,它自然会认为它们是模棱两可的。

总之,我的问题是,为什么在这种情况下,运算符模板不被认为是完美匹配的?

最佳答案

让我们把它分解成两个不同的问题:

1.为什么会产生编译错误?

struct C
{
operator bool () {return false;}
operator int () {return 1;}
};

由于 intbool 都可以隐式转换为 double,因此编译器无法知道应该使用哪个函数。它可以使用两种功能,并且没有一种优先于另一种。

<强>2。为什么模板化版本不完美?

struct C
{
template <typename T> operator T () {return 0.5;}
operator int () {return 1;}
};

为什么在请求 double 时调用 operator int()

The non-template function is called because a non-template function takes precedence in overload resolution. (Overloading function templates)

编辑:我错了!正如 Yan Zhou 在他的评论中提到的那样,正如我提供的链接中所述,模板化函数中的完美匹配优先于非模板化函数。

我测试了你的代码(用 g++ 4.7.2 编译),它按预期工作:它返回 0.5,换句话说,使用了模板函数!

EDIT2:我现在尝试使用 clang,我可以重现您描述的行为。由于它在 gcc 中正常工作,这似乎是 clang 中的一个错误。

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

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