mercredi 2 septembre 2020

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. There is some math inside to be done, so all the passed values to Sample() method will have to be converted to float.

What is a good elegant way to write this Convert() function? 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. Making specific Convert(std::chrono::duration<int64_t, std::nano> value) didn't work with a different version Convert(T value).

C++14 on gcc 9.3.0.

Aucun commentaire:

Enregistrer un commentaire