Are there cases where a typedef is absolutely necessary?

后端 未结 8 1326
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 01:21

Consider the following excerpt from the safe bool idiom:

typedef void (Testable::*bool_type)() const;
operator bool_type() const;

Is it possibl

8条回答
  •  眼角桃花
    2021-02-05 01:56

    A typedef is not a macro your second example is not equivalent to the first. In the first case your typedef is defining a functor then using that type in a cast operator of the functor type. In the second the operator is using bad syntax as there is no operator specified because there is no type. I'm not sure how to write it but there is a way usually.

    Typedefs aren't really necessary except for making human readable code in TMP and even then it depends on what kind of human you are.

    Since I can't come up with the alternative syntax maybe typedefs are necessary in some cases. I just thought of another one possibly. Say you had a template with specializations which contained a static method with a return type like below:

    template 
    struct WhateverHandler
    {
       typedef T rType;
       static rType Whatever() { return rType(); }
    };
    
    template <>
    struct WhateverHandler
    {
       typedef std::string rType;
       static rType Whatever() { return rType(); }
    };
    

    I think in this case also you would need the typedef in order to call the static method regardless of specialization as otherwise the method could confuse the compiler because the return types would differ but it wouldn't be a proper overload.

    template 
    struct WhateverUser
    {
       typename WhateverHandler::rType DoWhatever()
       {
           return WhateverHandler::template Whatever();
       }
    };
    

提交回复
热议问题