Reputation: 1339
Scenario
I have a C++ function which intakes a parameter as std::chrono::milliseconds
. It is basically a timeout value. And, it is a default parameter set to some value by default.
Code
#include <iostream>
#include <chrono>
void Fun(const std::chrono::milliseconds someTimeout = std::chrono::milliseconds(100)) {
if (someTimeout > 0) {
std::cout << "someNumberInMillis is: " << someNumberInMillis.count() << std::endl;
}
}
int main() {
unsigned int someValue = 500;
Fun(std::chrono::milliseconds(someValue))
}
Issue
All of above is okay but, when I call Fun
with a value then fails to compile and I get the following error:
No viable conversion from 'bool' to 'std::chrono::milliseconds' (aka 'duration >')
Question:
What am I doing wrong here? I want the caller of Fun
to be explicitly aware that it is using std::chrono::milliseconds
when it invokes Fun
. But the compiler doesn't seem to allow using std::chrono::milliseconds
as a parameter?
How use std::chrono::milliseconds
as a default parameter?
Environment
Compiler used is clang on macOS High Sierra
Upvotes: 6
Views: 5934
Reputation: 30831
With the other syntax errors fixed, this compiles without warnings in GCC 9:
#include <iostream>
#include <chrono>
void Fun(const std::chrono::milliseconds someNumberInMillis
= std::chrono::milliseconds(100))
{
if (someNumberInMillis > std::chrono::milliseconds{0}) {
std::cout << "someNumberInMillis is: " << someNumberInMillis.count()
<< std::endl;
}
}
int main()
{
unsigned int someValue = 500;
Fun(std::chrono::milliseconds(someValue));
}
Upvotes: 4