无法将std :: chrono :: duration与零

时间:2018-03-28 10:52:40

标签: c++11 chrono

在我正在处理的模板类中,我想检查std::chrono::duration是否为正的前提条件,但我的编译器抱怨它无法实例化所需的operator<模板。

这是问题的最小例子(不是我的原始容器):

 #include <chrono>
 #include <cassert>
 #undef NDEBUG

 template< typename VALUE >
 class Container final
 {
  public:
   using Interval = std::chrono::duration< unsigned int >;

   Container(const Interval interval_):
     interval(interval_),
     value(0)
     {
       assert(Interval::zero < interval_);
     }

  private:
   Interval interval;
   VALUE value;
 };

 template class Container< unsigned int >;

编译器抱怨assert语句,因此:

 In file included from /usr/include/c++/6/cassert:44:0,
             from main.cpp:2:
 main.cpp: In constructor ‘Container<VALUE>::Container(Container<VALUE>::Interval)’:
 main.cpp:15:29: error: no match for ‘operator<’ (operand types are ‘std::chrono::duration<unsigned int>()’ and ‘const Interval {aka const std::chrono::duration<unsigned int>}’)
        assert(Interval::zero < interval_);
          ~~~~~~~~~~~~~~~^~~
 In file included from main.cpp:1:0:
 /usr/include/c++/6/chrono:668:7: note: candidate: template<class _Clock, class _Dur1, class _Dur2> constexpr bool std::chrono::operator<(const std::chrono::time_point<_Clock, _Duration1>&, const std::chrono::time_point<_Clock, _Duration2>&)
        operator<(const time_point<_Clock, _Dur1>& __lhs,
        ^~~~~~~~
 /usr/include/c++/6/chrono:668:7: note:   template argument deduction/substitution failed:
 In file included from /usr/include/c++/6/cassert:44:0,
                  from main.cpp:2:
 main.cpp:15:31: note:   mismatched types ‘const std::chrono::time_point<_Clock, _Duration1>’ and ‘std::chrono::duration<unsigned int>()’
   assert(Interval::zero < interval_);
                           ^
 In file included from main.cpp:1:0:
 /usr/include/c++/6/chrono:489:7: note: candidate: template<class _Rep1, class _Period1, class _Rep2, class _Period2> constexpr bool std::chrono::operator<(const std::chrono::duration<_Rep1, _Period1>&, const std::chrono::duration<_Rep2, _Period2>&)
   operator<(const duration<_Rep1, _Period1>& __lhs,
   ^~~~~~~~
 /usr/include/c++/6/chrono:489:7: note:   template argument deduction/substitution failed:
 In file included from /usr/include/c++/6/cassert:44:0,
             from main.cpp:2:
 main.cpp:15:31: note:   mismatched types ‘const std::chrono::duration<_Rep1, _Period1>’ and ‘std::chrono::duration<unsigned int>()’
        assert(Interval::zero < interval_);

我做错了什么?

或者这是编译器错误?我的编译器是Debian 6上的g ++(Debian 6.3.0-18 + deb9u1)6.3.0 2017051。

1 个答案:

答案 0 :(得分:1)

尝试使用Interval::zero()Interval::zero是一个函数,因此您将持续时间与函数进行比较。

作为旁注,我建议在构造函数中将您的Interval参数设置为模板,以便您可以接受其他duragion比例(秒,ms,我们等)

   template < typename Interval2 >
   explicit Container(const Interval2 interval_):
     interval(interval_),
     value(0)
     {
       assert(Interval2::zero() < interval_);
     }

std::chrono::duration构造函数将根据Period参数类型透明地调整滴答计数。