没有从int到自定义类的可行转换
No viable conversion from int for custom class
我编写了一个UTF8字符类,使用以下方法:
typedef uint32_t CodePoint; // This is meant to represent any unicode character
explicit Char(const char c);
explicit Char(const CodePoint cp);
Char& operator=(const char c);
Char& operator=(const CodePoint cp);
但是当我试图通过传递一个数字来构造一个新类时,我得到了一个错误:
utf8::Char c = 0x20AC; // No viable conversion from int to utf8::Char
utf8::Char c(0x20AC); // Call to constructor of 'utf8::Char' is ambiguous
为什么我看到这些错误?
typedef uint32_t CodePoint; // This is meant to represent any unicode character
你意识到c++ 11为这个目的定义了一个不同的char32_t
类型吗?
utf8::Char c = 0x20AC; // No viable conversion from int to utf8::Char
这不是赋值,它是构造。这种语法称为复制初始化,相当于:
utf8::Char c = utf8::Char(0x20AC);
除了从int
到utf8::Char
的转换是隐式的,因此不能使用explicit
构造函数。
utf8::Char c(0x20AC); // Call to constructor of 'utf8::Char' is ambiguous
从int
到char
的转换并不比从int
到uint32_t
的转换更好或更差。
是否有一种方法可以说"使用
CodePoint
构造函数除了char
"。
是的,在c++类型系统中表示"一切"的通常方式是模板:
explicit Char(char c);
template<typename T>
explicit Char(T cp);
当实参为char
时,首选Char(char)
构造函数(因为重载解析更倾向于选择非模板而不是模板,否则它们会有歧义),对于其他所有内容,将使用构造函数模板。
因为您不希望模板构造函数接受所有类型,所以如果使用非整型调用它,您可能希望使其出错。在c++ 11中,你可以这样做:
template<typename T>
explicit Char(T cp)
{
static_assert(std::is_integral<T>::value, "utf8::Char should only be constructed from integral types");
}
0x20AC是数字,所以必须提供另一个重载构造函数。
相关文章:
- 将文件复制到自定义位置,存在字符串转换问题
- C++ 通过自定义赋值运算符隐式转换函数参数
- 类型转换自定义结构
- 自定义类型转换运算符在转发引用上调用时不起作用(当对象按值传递时有效)
- 将字符串转换为自定义类
- 自定义函数转换错误?
- 将 OpenGL 坐标系统转换为自定义并返回
- 如何将CString转换为使用WCHAR的Windows API和自定义函数?
- 如何在<typename> <long> 不更改给定代码的情况下将自定义向量与 STL 向量相互转换?
- 使用自定义转换运算符的不明确性
- 如何支持any_cast将自定义类强制转换为字符串
- PyQt5:使用自定义信号时 int 对象的错误转换
- 自定义Clang将C 代码转换为C
- 自定义文本到语音转换中的语音
- C 功能指针用于将QVariant转换为{自定义类型
- 使用自定义分配器和std ::向量的std ::向量子类之间的转换
- 如何重写 AcDbEntity::transformBy 以在移动或缩放时获取自定义实体转换
- 不允许对自定义类型进行多次隐式转换?
- 可视类型转换自定义 C++ 类
- 如何在VS2012中转换自定义类型为字符串