How to pass std::chrono::duration as an argument to a function
06:25 25 May 2026
In the below code how do I pass std::chrono::duration type as an argument to a function? Inside the main function I'm able to declare a variable of type std::chrono::duration but while passing that same argument to a function it throws an error. Can somebody explain this behavior?
#include
#include
#include
// throws an error here
void foo(const std::chrono::duration& d) {
std::cout << d.count() << std::endl;
}
int main() {
const auto s = std::chrono::steady_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(3));
const auto e = std::chrono::steady_clock::now();
// doesn't throw an error here
const std::chrono::duration d = e - s;
std::cout << d.count() << std::endl;
}
Error
:5:10: error: missing template argument list after 'std::chrono::duration'; template placeholder not permitted in parameter
5 | void foo(const std::chrono::duration& d) {
| ^~~~~
| <>
:5:10: note: or use 'auto' for an abbreviated function template
In file included from /cefs/38/383ad2f84cbd57a52fd68bbe_consolidated/compilers_c++_x86_gcc_16.1.0/include/c++/16.1.0/chrono:51,
from :1:
/cefs/38/383ad2f84cbd57a52fd68bbe_consolidated/compilers_c++_x86_gcc_16.1.0/include/c++/16.1.0/bits/chrono.h:68:13: note: 'template class std::chrono::duration' declared here
68 | class duration;
| ^~~~~~~~
: In function 'void foo(...)':
:6:18: error: 'd' was not declared in this scope
6 | std::cout << d.count() << std::endl;
| ^
Compiler returned: 1
c++c++-chrono
Your Answer
lock_outline
You need to log in to submit an answer.
Privacy & Cookie Consent
We use cookies to ensure the best experience on our website. This includes analytics, personalization, and marketing purposes. Some cookies are essential for the website to function properly.
By clicking "Accept", you consent to our use of cookies. You can read more about how we use cookies and how you can change your preferences in our Privacy Policy.