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

标签 c++ templates

给定一个任意数字类型,它可能是也可能不是 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/

相关文章:

c++ - 结合 Eigen 和 CppAD

c++ - gcc - 在一个命令中链接和编译

c++ - 从 5 个加扰的序列中导出有序序列

C++ : Creating a parametrized pointer from a string

c++ - 如何在C++中逐行读取字符串

c++ - 如何制作通用类方法?

c++ - 将 C++20 模板化 Lambda 传递给函数,然后调用它

c++ - 为什么使用 GetPixel 会导致 "undefined reference"?

C++ 部分模板 模板特化

c++ - template-name<TT> 是推导的上下文吗?