C++转换具有运算符重载的模板
C++ converting templates with operator overload
我有一个模板类,我尝试通过运算符重载将模板版本转换为另一个模板验证
enum MyTypes {A,B,C}
template<MyTypes T>
MyClass {
const static MyType type_ = T;
template<MyTypes U>
MyClass<U> convert(MyTypes t) {
MyType<U> ret = MyType<U>();
....
return r;
}
template<MyTypes U>
MyClass<U> operator()() {
return convert(U);
}
}
但是,这会产生(在 gcc,c11 上)
conversion from MyClass<0u> to non-scalar type MyClass<1u> requested
删除模板函数并尝试
MyClass<A> operator()() {
MyClass<A> a = MyClass<A>();
...
return a;
}
抛出
the error operator cannot be overloaded
基本上,我想要实现的是,如果我有
MyClass<A> a = MyClass<A>;
MyClass<B> b = a;
它基于 a 和转换创建一个新的 MyClass。知道我在这里的错误是什么吗?
编辑:我扔掉了一个模板函数,只是留下了运算符
template<MyTypes U>
MyClass<U> operator()() {
MyClass<U> ret = MyClass<U>();
...
return ret;
}
但这仍然产生
conversion from MyClass<0u> to non-scalar type MyClass<1u> requested
尝试做时
MyClass<B> = a
下面转换值并允许赋值:
#include <iostream>
#include <string>
enum MyTypes { A, B, C };
template<MyTypes T>
struct MyClass{
const static MyTypes type_ = T;
std::string history{"started as " + std::to_string(T)};
template<MyTypes U>
operator MyClass<U> () {
return {history+" then became " + std::to_string(U)};
}
};
int main()
{
MyClass<A> a;
MyClass<B> b = a;
MyClass<C> c = b;
std::cout << a.history << 'n';
std::cout << b.history << 'n';
std::cout << c.history << 'n';
}
输出:
started as 0
started as 0 then became 1
started as 0 then became 1 then became 2
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用