I am trying to use alias for std::chrono and std::chrono::duration_cast<std::chrono::seconds> which are throwing compilation errors. I included <chrono> header file. Below is the code:
#include <chrono>
class abc {
public:
using co = std::chrono; // Throwing compilation error
using coDurationCast = std::chrono::duration_cast<std::chrono::seconds>; // Throwing compilation error
using timeType = std::chrono::time_point<std::chrono::system_clock>; // Surprisingly this is working fine
};
Error:
error: ‘chrono’ in namespace ‘std’ does not name a type
error: ‘std::chrono::duration_cast’ in namespace ‘std::chrono’ does not name a template type
I am unable to understand why it is throwing this error. Surprisingly, the alias is working for std::chrono::time_point<<std::chrono::system_clock>>.
Can anyone please help me to understand why it is throwing this error?
There are 3 different cases here (mostly summary of the info from the comments):
using co = std::chrono;:
std::chrono is a namespace. You cannot create a namespace alias in class scope. Also the proper syntax for a namespace alias (at global scope) is:
namespace co = std::chrono;
using coDurationCast = std::chrono::duration_cast<std::chrono::seconds>;:
std::chrono::duration_cast is a function template. You cannot create an alias for a function or a function template.
What you can do is bring the function into the current namespace by using:
using std::chrono::duration_cast;
using timeType = std::chrono::time_point<std::chrono::system_clock>;:
std::chrono::time_point is a class template, and std::chrono::time_point<std::chrono::system_clock> is therefore a concrete type.
It is valid to create an alias to a type, and therefore this line is valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With