从std :: complex< MyType>进行类型转换到std :: complex< double> [英] Type conversion from std::complex<MyType> to std::complex<double>

查看:67
本文介绍了从std :: complex< MyType>进行类型转换到std :: complex< double>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现用户定义的算术类型的类 MyType 。此类提供以下转换运算符

  struct MyType 
{...
运算符double()
{
return to_double(); //将我的类型转换为双精度值
}
...};

按如下所示使用此类可以正常工作:

  double d = MyType(1); 

但是,使用此类作为std :: complex中的类型,例如

  #include< complex> 
std :: complex< double> c = std :: complex< MyType>(1,1);

失败,并出现以下编译器错误:

 错误:从'std :: complex< MyType>'转换为非标量类型'std :: complex< double>'要求

感谢您为解决此问题提供的帮助。



解决方案


专业化 std :: complex< float> std :: complex< double> std :: complex< long double> 是用于表示和处理复数的LiteralType。 / p>

未指定实例化其他任何类型的模板复合体的效果。


所以 std :: complex< MyType> 是有问题的 ...


忽略该部分,


而< a href = https://en.cppreference.com/w/cpp/numeric/complex/complex rel = nofollow noreferrer> std :: complex< T> 具有通用骗局转换构造函数,专门化 std :: complex< double> 仅提供其他浮动复杂版本的转换。


但是 operator = 允许通用所有版本的转换(尽管只有Msvc接受代码)。


您必须提供自己的(显式/命名)转换功能:

  std :: complex< double> to_complex_double(std :: complex< MyType>& c)
{
#if 0
std :: complex< double> RES;
res = c; // gcc / clang不接受。
美元的回报;
#else
return {c.real(),c.imag()};
#endif
}


I have a class MyType that implements a user-defined arithmetic type. This class provides the following conversion operator

struct MyType 
{ ...
  operator double()
  { 
    return to_double(); // This converts my type to a double value
  }
... };

Using this class as follows works fine:

double d = MyType(1);

However, using this class as type within std::complex, e.g.

#include <complex>
std::complex<double> c = std::complex<MyType>(1,1);

fails with the following compiler error:

error: conversion from 'std::complex<MyType>' to non-scalar type 'std::complex<double>' requested

Any help to solve this problem is appreciated.

Matthias

解决方案

The specializations std::complex<float>, std::complex<double>, and std::complex<long double> are LiteralTypes for representing and manipulating complex numbers.

The effect of instantiating the template complex for any other type is unspecified.

So std::complex<MyType> is "problematic"...

Ignoring that part,

whereas std::complex<T> has generic converting constructor, specialization std::complex<double> only provide conversions from other floating complex versions.

But operator= allows generic conversion for all versions (Only Msvc accepts the code though).

You have to provide your own (explicit/named) conversion function:

std::complex<double> to_complex_double(std::complex<MyType>& c)
{
#if 0
     std::complex<double> res;
     res = c; // gcc/clang doesn't accept that.
     return res;
#else
     return {c.real(), c.imag()};
#endif
}

这篇关于从std :: complex&lt; MyType&gt;进行类型转换到std :: complex&lt; double&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆