C++自动类型转换:容器类的错误行为
C++ automatic type casting : wrong behaviour for a container class
我正在实现一些类,用于在非常小的常数大小向量和矩阵上进行线性代数运算。Currenty,当我这样做时:
MyMathVector<int, 3> a ={1, 2, 3};
MyMathVector<double, 3> b ={1.3, 2.3, 3.3};
std::cout<<"First = "<<a+b<<std::endl;
std::cout<<"Second = "<<b+a<<std::endl;
然后是First = {2, 4, 6}
和Second = {2.3, 4.3, 6.3}
,因为编译器将第二个元素强制转换为第一个元素类型。有没有什么"简单"的方法可以提供与原生C++中相同的自动铸造:int+double=double,double+int=double?
非常感谢。
编辑:根据答案中给出的语法,我得到了运算符+。但我尝试了以下语法,编译失败并出现错误:expected a type, got ‘std::common_type<T, TRHS>::type’
#include <iostream>
#include <type_traits>
template<class T> class MyClass
{
public:
MyClass(const T& n) : _n(n) {;}
template<class TRHS> MyClass<typename std::common_type<T, TRHS>::type> myFunction(const MyClass<TRHS>& rhs)
{
return MyClass<std::common_type<T, TRHS>::type>(_n*2+rhs._n);
}
T _n;
};
int main()
{
MyClass<double> a(3);
MyClass<int> b(5);
std::cout<<(a.myFunction(b))._n<<std::endl;
}
这种语法有什么问题?
使用std::common_type
:
template <std::size_t s, typename L, typename R>
MyMathVector<typename std::common_type<L, R>::type, s> operator+(MyMathVector<L, s> const& l, MyMathVector<R, s> const& r)
{
// do addition
}
Ot在成员函数的情况下(在类主体中,其中T
和s
可见):
template <typename TRHS>
MyMathVector<typename std::common_type<T, TRHS>::type, s> operator+(MyMathVector<TRHS, s> const& rhs) const
{
// do addition
}
使用std::common_type
特性来计算混合运算的正确结果类型。
链接页面甚至有一个与您的案例非常相似的示例。
绝对;使用decltype
:
template<typename Other>
auto operator+(const MyMathVector<Other, size> &other)
-> MyMathVector<decltype(std::declval<T>() + std::declval<Other>()), size>;
作为一个非成员运算符,最好说出实际引用向量成员的意思:
template<typename size, typename L, typename R>
auto operator+(const MyMathVector<L, size> &l, const MyMathVector<R, size> &r)
-> MyMathVector<decltype(l[0] + r[0]), size>;
相关文章:
- 错误:需要类名(链表c++)
- 如何正确实现容器类中元素的更改?
- C++ 用于检查容器类中是否存在函数和隐式推导规则的概念
- 错误:基类在从基类父派生类 Son 时未定义
- 错误:类没有名为"ThisW"的成员;你是说"这个"吗?但是代码没有说"ThisW",它已经说了"This"
- 容器类中的类迭代器
- C++错误:在类中取消对main的定义引用
- 返回持有 std::mutex 锁的 RAII 容器类
- 错误:"类 std::vector<Shape*>"没有名为"sort"的成员
- 错误C++:类不命名类型
- C++ 如何在容器类复制构造函数中复制分配器对象
- 如何使用迭代器设计模式为 C++ 中的包装容器类提供多个迭代器?
- 如何在模板容器类中实现复制构造函数和赋值运算符
- 在我的 cpp 或头文件中找不到错误,类构建失败
- C++线程错误 - 带有类参数的编译时错误
- 分段错误 - 分配类困难
- 使用导致分段错误的类C++中的堆栈实现
- 在容器类中使用带有共享_ptr/unique_ptr的虚拟对象
- C++自动类型转换:容器类的错误行为
- 运行容器类程序时显示错误