多种转换功能作为“操作员自动"在班上 [英] Multiple conversion functions as "operator auto" in class

查看:26
本文介绍了多种转换功能作为“操作员自动"在班上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中

struct S {
    operator auto() { return 42; }
};

operator auto 等价于 operator int 因为实际类型是从文字 42 推导出来的,该类型是 int.如果我写 42.5 而不是 42 那么 operator auto 将被解释为 operator double 显而易见的原因.但是当我同时使用两者时,所有三个主要编译器(gcc、clang、msvc)都出现编译器错误:

operator auto is equivalent to operator int since actual type would be deduced from the literal 42 and that type is int. If I write 42.5 instead of 42 then operator auto would be interpreted as operator double for obvious reason. But when I use both at the same time I got a compiler error for all three major compilers (gcc, clang, msvc):

struct S {
    operator auto() { return 42; }
    operator auto() { return 42.5; }
};

实际的错误信息因编译器而异,但原因都是一样的:函数已经定义".

Actual error messages are vary among compilers, but the reason is the same: "Function already defined".

我无法在标准中找到为什么不能在一个类中同时使用两个 operator auto(具有不同的返回类型).有人可以指出标准的条款,其中该组转换函数被认为是被禁止的吗?

I can't find in standard why the both operator auto (with different return type) can't be used simultaneously in one class. Could someone point me to the standard's clause where that set of conversion functions considered as forbidden?

推荐答案

基于 Fedor 的 answer 的想法,您甚至可以使用 至少 12 个 auto 类似运算符 和不同的限定符:

Based on idea from Fedor's answer you can even use at least 12 auto like operators with different qualifiers:

#include <iostream>

struct S {
    operator auto() { return 42; }
    operator auto() const { return '+'; }
    operator auto() volatile { return 44LL; }
    operator const auto() { return 45.5; }
    operator const auto() const { return 46.5f; }
    operator const auto() volatile { return 47L; }    
    operator volatile auto() { return 48ULL; }
    operator volatile auto() const { return 49U; }
    operator volatile auto() volatile { return 50UL; }
    operator decltype(auto)() { return 51.5L; }
    operator decltype(auto)() const { return 52.5L; }
    operator decltype(auto)() volatile { return 53.5L; }
};

int main() {
    const S s;
    std::cout << (int)(S)s << "\n";
    std::cout << (char)s << "\n";
    std::cout << (long long)(volatile S)s << "\n";
    
    std::cout << (double)(S)s << "\n";
    std::cout << (float)s << "\n";
    std::cout << (long)(volatile S)s << "\n";
    
    std::cout << (unsigned long long)(S)s << "\n";
    std::cout << (unsigned)s << "\n";
    std::cout << (unsigned long)(volatile S)s << "\n";
    
    std::cout << (long double)(S)s << "\n";
    std::cout << (long double)s << "\n";
    std::cout << (long double)(volatile S)s << "\n";
}

这篇关于多种转换功能作为“操作员自动"在班上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆