【问题标题】:Ignore 'long' specifier for custom type in c++忽略 C++ 中自定义类型的“长”说明符
【发布时间】:2022-01-14 05:50:35
【问题描述】:

我有一个类型和一个模板类

#ifdef USE_QUAD
using hybrid = __float128;
#else
using hybrid = double;
#endif

template<typename T>
struct Time {
    int day;
    long T dayFraction; // This is an example, I need both in here, T and long T;
};

让事情变得复杂:一个嵌套类

template<typename T>
struct State {
    Time<T> time;
    std::vector<T> position;
}

现在我想在我的代码中同时使用 hybriddouble 的类,比如

State<hybrid> stateH; // sometimes precision needed
State<double> stateD; // precision never needed

让预处理器处理应该是什么混合。

然而,如果hybrid = double,则代码可以完美编译,但如果hybrid = __float128 编译,则没有那么多,因为Time 类中的long T dayFraction;

是否有解决方法来定义类似的别名

using long __float128 = float128;

?

我有一个解决方法来定义longHybrid,例如:

#ifdef USE_QUAD
using hybrid     = __float128;
using longHybrid = __float128;
#else
using hybrid     = double;
using longHybrid = long double;
#endif

但是转发两个模板参数会影响一些代码,感觉有点多余。 我很想听听任何想法。

【问题讨论】:

    标签: c++ templates alias quadruple-precision


    【解决方案1】:

    Tdouble 时,您实际上不能写long T 并期望它被解释为long double。如果它适合你,那是你的编译器的一个不可移植的怪癖。

    如果您想要类型的“常规”和“长”版本,double 不同但float128 相同,一种方法是定义这样的模板:

    template <typename T> struct Longer {
        using type = T;
    };
    template <> struct Longer<double> {
        using type = long double;
    };
    

    使用typename Longer&lt;T&gt;::type 代替struct Time 中的long T

    【讨论】:

    • 我刚刚实现了这个,它工作正常。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 2013-08-23
    • 2016-01-15
    • 2015-01-21
    相关资源
    最近更新 更多