gpt4 book ai didi

c++ - 如何确定任意 C++ 数字类型的实部类型?

转载 作者:行者123 更新时间:2023-11-30 02:57:03 24 4
gpt4 key购买 nike

给定一个任意数字类型,它可能是也可能不是 std::complex类型,我想获得代表该类型“实部”的类型。例如std::complex<double>的实部是double , 和 double 的实部是double本身。下面的示例使用 C++ 部分模板特化来完成此操作。 @mfontanini 在下面发布了一个更简单的方法。

我的问题:是否有 Boost 库中已经提供的直接方法?如果是这样,我一直找不到它。

#include <complex>
#include <boost/type_traits/is_complex.hpp>

template <typename T>
class RealPart
{
private:
template <bool, typename>
class ResultType;

// complex type -> real type
template <typename T1>
class ResultType<true, T1>
{
public:
typedef typename T1::value_type type;
};

// real type -> real type
template <typename T1>
class ResultType<false, T1>
{
public:
typedef T1 type;
};

public:
// define result_type, making use of the template specialization above
typedef typename ResultType<boost::is_complex<T>::value, T>::type result_type;
};


// both will become doubles
RealPart<std::complex<double> > a;
RealPart<double> b;

最佳答案

不需要使用类型特征,你可以只使用模板特化来完成同样的事情:

// general case
template <typename T>
struct RealPart {
typedef T type;
};

// std::complex
template <typename T>
struct RealPart<std::complex<T> > {
typedef T type;
};

这是否已经在 boost 的某处实现,我真的不知道。

关于c++ - 如何确定任意 C++ 数字类型的实部类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14925544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com