模板类的用户定义运算符上的 C++ 隐式转换
c++ implicit conversion on user-defined operator for template classes
我有一个结构模板A<x>
和一个带有int
的+
运算符。
#include <iostream>
template<int x>
struct A{
int a;
};
template<int x>
int operator+(A<x> a, int b){
return a.a+b;
}
我创建了一个结构模板B<x>
,可以转换为A<x>
。
template<int x>
struct B{
int b=3;
operator A<x>(){
return {b+10};
}
};
现在我希望在调用B<x> + int
B<x>
时将转换为A<x>
。
int main(){
std::cout<<(A<12>{9}+10)<<std::endl;//OK
std::cout<<(B<12>{9}+10)<<std::endl;//Error
return 0;
}
我阅读了模板类重载运算符时的隐式转换并编写了
template<int x>
struct B{
int b=3;
operator A<x>(){
return {b+10};
}
friend int operator+(A<x> a, int b);
};
,但它不起作用,因为声明的friend int operator+(A<x> a, int b)
与template<int x> int operator+(A<x> a, int b)
不匹配.
我阅读了C++ - 如何为类模板声明函数模板友元并制作了友元声明模板,但由于无法推断模板参数而不起作用。
当然,我可以为 A 和 B 编写 operator+,但我有几十个运算符,我不想这样做。
正确的方法是什么?
看看为A
制作非成员operator+
的两种方法,我们可以将其作为函数模板:
template <int x>
int operator+(A<x>, int);
这与B<x>
不匹配,因为我们只是在进行模板扣除,不允许转化。
或者,我们可以将其设为非模板的朋友:
template <int x>
struct A {
friend int operator+(A a, int );
};
这也与B<x>
不匹配,因为名称查找不会考虑该功能。除非,也就是说,我们告诉它:
template <int x>
struct B {
friend int operator+(A<x>, int ); // NB: not a template
};
现在,将考虑我们原始的非模板operator+
,转换将根据需要执行,并且您的代码打印 29。
我尝试使用以下(可运行(代码编辑 Barrys 答案,该代码产生正确的输出,但在那里被拒绝。
我会在这里添加它,以防其他人好奇。
#include <iostream>
template <int x>
struct A {
int a;
friend int operator+(A a, int b) { return a.a + b; }
};
template <int x>
struct B {
int b;
operator A<x>() { return {b+10}; }
friend int operator+(A<x>, int );
};
int main() {
std::cout << (A<12>{9} + 10) << std::endl;
std::cout << (B<12>{9} + 10) << std::endl;
}
哪些打印
19
29
您可能已经看到了这一点,但至少仍然可以进行显式转换,并且可能很有用:
int main(){
std::cout<<(A<12>{9}+10)<<std::endl; // prints 19
std::cout<<(static_cast<A<12>>(B<12>{9})+10)<<std::endl; // prints 29
return 0;
}
我希望它能帮助你。
我有模板化的朋友operator+
从A<x>
派生并编译,但是在调用friend operator+
变量后,a
是uninit的,所以我得到了即时值。您必须以某种方式设置a
这似乎有效。
#include <iostream>
template<int x>
struct A
{
int a{x};
};
template<int x>
int operator+(A<x> a, int b)
{
return a.a+b;
}
template<int x>
struct B : A<x>
{
int b;
template<int U>
friend int operator+(A<U> a, int b);
};
int main(void)
{
std::cout<< (A<20>{}+10)<<std::endl; // prints 30
std::cout<< (B<10>{}+10)<<std::endl; // prints 20
return 0;
}
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 复制列表初始化的隐式转换的等级是多少
- 正在将指针转换为范围
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 是否可以从int转换为enum类类型
- 了解 GLM- openGL 中的相机转换
- 将无符号char*转换为std::istream*C++