相关疑难解决方法(0)

使用模板进行隐式类型转换

我有一个模板 class A

template <unsigned int m>
class A
{
public:
    A(int) {}
};
Run Code Online (Sandbox Code Playgroud)

哪个有构造函数int.我有一个手术:

template<unsigned int m>
A<m> operator+(const A<m>&, const A<m>&)
{
    return A<m>(0);
}
Run Code Online (Sandbox Code Playgroud)

但是当我打电话时:

A<3> a(4);
A<3> b = a + 5;
A<3> c = 5 + a;
Run Code Online (Sandbox Code Playgroud)

我想int隐式转换为A,但编译器会抛出错误.

有没有优雅的方法来启用隐式转换而不使用以下解决方案:

  • a + A<m>(5)
  • operator+<3>(a, 5)

c++ templates type-conversion

37
推荐指数
2
解决办法
2万
查看次数

标签 统计

c++ ×1

templates ×1

type-conversion ×1