“using” keyword in C++

前端 未结 1 1647
栀梦
栀梦 2020-12-29 13:27

I am learning C++. And my professor uses some code which is something like

using filePath = std::string;
using setOfPaths = std::set;
using i         


        
1条回答
  •  离开以前
    2020-12-29 14:11

    The using keyword is used to define type aliases. The reasons your professor is using it are:

    • readability
    • being more descriptive
    • avoid unnecessary typename

    Readability and descriptiveness

    You can use type aliases to semantically (and only that) restrict a specific type, making the name more descriptive for the specific use.

    An example is:

    using fileName = std::string;
    

    The fileName alias is used to describe a file name string, not just any string. This makes for readable function signatures too.

    I feel like I have to iterate this again: it's simply an alias. Any function taking fileName as an argument will work just fine with any std::string argument.

    Unnecessary typenames

    Some may seem unnecessary, like:

    using setOfPaths = std::set;
    

    but in some cases they can be actually used to avoid having to specify typename in situations like:

    template
    struct something {
        using something_iter = typename std::set::iterator;
    };
    

    with:

    template
    using itertype = typename Container::iterator;
    
    template
    struct something {
        using something_iter = itertype>;
    }; 
    

    By moving typename in a specific alias we can reuse itertype in multiple other occasions effectively avoiding typename.

    A note on typedef

    There's another way to define type aliases: typedef. That keyword is inherited from C and does not allow for templated aliases, like:

    template
    using vec = std::vector;
    

    A note on type safety

    This is not actually any more type safe than not using aliases at all. Again, fileName and std::string are exactly the same type. You can use both interchangeably.

    A possible next step would be to define a specific fileName class/struct type with its own specific invariants.

    0 讨论(0)
提交回复
热议问题