0

The code provided below failed to compile. The compiler blames candidate template ignored: couldn't infer template argument 'Rep2'. What I expect is to provide a d1 and use the default value as d2.

Is it due to the default value d2=std::chrono::minutes(1) which confused the type deduction? However, the default is the second argument which is the desired default as there is no 2nd argument provided in the BAr bar{...} statement.

#include<chrono>

struct Bar
{
  std::chrono::nanoseconds duration1;
  std::chrono::nanoseconds duration2;

  Bar()=delete;
  template<class Rep,class Period,class Rep2,class Period2>
  Bar(
      const std::chrono::duration<Rep, Period> &d1,
      const std::chrono::duration<Rep2, Period2> &d2=std::chrono::minutes(1)):
      duration1(std::chrono::duration_cast<std::chrono::nanoseconds>(d1)),
      duration2(std::chrono::duration_cast<std::chrono::nanoseconds>(d2))
  {
  }
};

int main()
{
  Bar bar{std::chrono::hours(7)};
}

  • Thanks for the link... so, is it not a good idea to provide a default value for the template arguments in general? For this problem, I can think of the ways to avoid the error by providing 2 ctor: ` Bar(d1);` which initialize `duration2` to the default value, and the other ctor `Bar(d1,d2);` has no default argument. – Victor Tsang May 25 '20 at 06:48
  • 1
    No you just need to add defaults for `Rep2` and `Period2` – Alan Birtles May 25 '20 at 06:58
  • As your question is already marked as answered I will add my remarks as a comment. `std::chrono::duration` allows for implicit casts to a smaller unit as there is no loss of information. In your example, there is no need to use templates at all as std::chrono::nanoseconds is the smallest duration interval possible. Check this example on godbolt: https://gcc.godbolt.org/z/EvRQcJ – Simon Kraemer May 25 '20 at 09:02

0 Answers0