Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

c++ - Why can't virtual functions use return type deduction?

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).

Therefore the following program is ill-formed:

struct s
{
    virtual auto foo()
    {
    }
};

All I can find for the rationale is this vague one-liner from n3638:

virtual

It would be possible to allow return type deduction for virtual functions, but that would complicate both override checking and vtable layout, so it seems preferable to prohibit this.

Can anyone provide further rationale or give a good (code) example that agrees with the above quote?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...