Why can't virtual functions use return type deduction?

前端 未结 3 1062
忘掉有多难
忘掉有多难 2021-01-07 17:11

n3797 says:

§ 7.1.6.4/14:

A function declared with a return type that uses a placeholder type shall not be virtual (10.3).

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-07 17:40

    The rationale that you included is reasonably clear: naturally, virtual functions are meant to be overridden by subclasses, so you as the designer of the base class should make it as easy as possible for people who inherit your class to provide a suitable override. However, if you use auto, figuring out the return type for the override becomes a tedious task for a programmer. Compilers would have less of a problem with it, but humans would have many opportunities to get confused.

    For example, if you see a return statement that looks like this

    return a * 3 + b;
    

    you would have to trace the program back to the point of declaration of a and b, figure out the type promotions, and decide what the return type shall be.

    It appears that the language designers figured out that this would be rather confusing, and decided against allowing this feature.

提交回复
热议问题