3

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?

7
  • 3
  • 4
    namespace co = std::chrono; Not allowed at class scope though. Commented Sep 4 at 23:09
  • 5
    std::chrono::duration_cast is a function template; you can't create an alias of a function. std::chrono::time_point is a class template; you can create an alias for a type. In other words: if you have class C{}; void f(); you can write using C_alias = C; but not using f_alias = f; Commented Sep 4 at 23:16
  • 3
    std::chrono::time_point<std::chrono::system_clock> is a type, and you can create aliases to types. std::chrono::duration_cast<std::chrono::seconds> is a function. and you cant create aliases to functions. Commented Sep 4 at 23:16
  • 1
    But you can bring a function into the current nmaespace with: using std::chrono::duration_cast; Commented Sep 5 at 0:17

1 Answer 1

4

There are 3 different cases here (mostly summary of the info from the comments):

  1. 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;
    
  2. 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;
    
  3. 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.