c++ - 转换不明确。标准隐式转换无法选择强制转换运算符

标签 c++ templates casting

我有一个自定义类型,描述为

struct A {
    double dbl_;
    bool boo_;
    operator double() const { return dbl_; }
    //operator bool() const { return boo_; }
};

现在我想将其转换为简单类型。当 operator bool() 未定义时,a 可以隐式转换为任何简单类型 int、unsigned、float 等。但是使用 operator bool() 转换不明确。

A a;
cout << (double) a << endl;
cout << (float) a << endl; //error: conversion from 'A' to 'float' is ambiguous; candidates are: A::operator bool() const; A::operator double() const
cout << (int) a << endl;  // the same
cout << (char) a << endl; // the same
return 0;

cpp.sh 上的可运​​行代码

我知道有几种方法可以解决这个问题:

1.为所有预期类型添加类型转换运算符。

 operator int() const { return (int)dbl_; }
 // and so on...

这看起来像是不好的做法。

2.使用 template with restricted types

template<class T, class...> struct is_any_of: std::false_type{};
template<class T, class Head, class... Tail>
struct is_any_of<T, Head, Tail...> : std::conditional<
        std::is_same<T, Head>::value,
        std::true_type,
        is_any_of<T, Tail...> >::type
{};

template<
        class T,
        class = typename std::enable_if<is_any_of<T, int, float, unsigned, double>::value>::type
>
operator T() const {
    if(type_ != Type::NUMBER) throw Node::Exception("not is number");
    return dbl_;
}

3.在dbl_中保存bool值,因为只使用其中一个。不酷,对我来说。

可能存在更完善的解决方案?喜欢

operator bool() const no_implicit_conversation_to_other_types_specifier { return boo_; }

问题最多是C++的理论。

更新 no_implicit_conversation_to_other_types_specifier 是显式

explicit operator bool() const { return boo_; }

Run .

最佳答案

使所有转换运算符显式(以防止隐式转换)将是一个好的开始:

struct A {
    double dbl_;
    bool boo_;
    explicit operator double() const { return dbl_; }
    explicit operator bool() const { return boo_; }
};

不确定,但我想这也有助于避免歧义。

关于c++ - 转换不明确。标准隐式转换无法选择强制转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35275605/

相关文章:

F# 测量单位,类型转换时不丢失测量类型

c++ - 无法更改图像Mat opencv中的所有像素

c++ - 将局部变量分类为 C++11 之前的谓词

c++ - 枚举作为模板

javascript - 如何检查 Dust.js 中不区分大小写的值?

ios - 如何在Objective-C的NSNumber后面附加一个字符?

C++: "trait"和 "meta-function"是同义词吗?

c++ - 如何通过 Q_PROPERTY 将指向 Q_GADGET 的指针暴露给 QML

c++ - 将除字符串以外的所有类型按值传递给模板函数

python - swig,从列表到非标准 vector