即使只是尝试开始,我也会收到此代码的错误:
note: candidate template ignored: could not match 'double' against 'long'
::
#include <numeric>
#include <chrono>
using namespace std::chrono_literals;
// how to write a function that will take any duration and turn it
// into a float representation of seconds?
template <class T>
void go(std::chrono::duration<double, T> d) {
// what I want to do (that may not work because I haven't gotten this far):
float seconds = std::chrono::duration_cast<std::chrono::seconds>(d);
}
int main()
{
go(1ms);
go(1s);
}
答案 0 :(得分:4)
我只能猜测你想要完成什么,这是我最好的猜测:
#include <chrono>
#include <iostream>
using namespace std::chrono_literals;
void go(std::chrono::duration<float> d) {
std::cout << d.count() << '\n';
}
int main()
{
go(1ms);
go(1s);
}
输出:
0.001
1
答案 1 :(得分:2)
转换为float并调用count():
#include <iostream>
#include <numeric>
#include <chrono>
template< class T, class P >
float to_secs(std::chrono::duration< T, P > t)
{
std::chrono::duration< float > f = t;
return f.count();
}
int main(int argc, char*argv[])
{
std::cout << to_secs(std::chrono::milliseconds(1)) << std::endl;
std::cout << to_secs(std::chrono::minutes(1)) << std::endl;
std::cout << to_secs(std::chrono::hours(1)) << std::endl;
// output:
// 0.001
// 60
// 3600
return 0;
}
答案 2 :(得分:0)
template<typename duration_t> float seconds(const duration_t &d);
template<class Rep, class Period>
float seconds(const std::chrono::duration<Rep, Period> &d)
{
typedef std::chrono::duration<Rep, Period> duration_t;
auto one_second=std::chrono::duration_cast<duration_t>
(std::chrono::seconds(1)).count();
if (one_second == 0)
return d.count() *
std::chrono::duration_cast<std::chrono::seconds>
(duration_t(1)).count();
else
return float(d.count())/one_second;
}