模板类的用户定义运算符上的 C++ 隐式转换

c++ implicit conversion on user-defined operator for template classes

本文关键字:C++ 转换 定义 用户 运算符      更新时间:2023-10-16

我有一个结构模板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> + intB<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;
}