简体   繁体   English

特定类型的 C++ 模板

[英]C++ template for specific type

So I have this little template class:所以我有这个小模板类:

template <typename T, typename std::enable_if<std::is_arithmetic<T>{} || std::is_same<T, std::chrono::duration<int64_t, std::nano>>{}, int>::type = 0>
class Accumulator
{
  public:
    void Sample(const T value) {
        value_ = Convert(value);
    }
  private:
    float value_;
}

It needs to work for all arithmetic types and std::chrono::duration<int64_t, std::nano> type.它需要适用于所有算术类型和std::chrono::duration<int64_t, std::nano>类型。 There is some math inside to be done, so all the passed values to Sample() method will have to be converted to float .内部有一些数学运算需要完成,因此所有传递给Sample()方法的值都必须转换为float

What is a good elegant way to write this Convert() function?编写这个Convert()函数的好方法是什么? I've tried writing an entire version of Accumulator for std::chrono::duration<int64_t, std::nano> type, but it looked like a code duplication.我已经尝试为std::chrono::duration<int64_t, std::nano>类型编写一个完整版本的Accumulator ,但它看起来像代码重复。 Making specific Convert(std::chrono::duration<int64_t, std::nano> value) didn't work with a different version Convert(T value) .使特定的Convert(std::chrono::duration<int64_t, std::nano> value)不适用于不同版本的Convert(T value)

C++14 on gcc 9.3.0. gcc 9.3.0 上的 C++14。

template <typename T, typename std::enable_if<std::is_arithmetic<T>{} || std::is_same<T, std::chrono::duration<int64_t, std::nano>>{}, int>::type = 0>
class Accumulator
{
  public:
    void Sample(const T value) {
        value_ = Convert(value);
    }
  private:
    float value_;
};
template <class U>
float Convert(U value) {
   // default overload
}
inline float Convert(std::chrono::duration<int64_t, std::nano> value) {
    // specialization for duration
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM