On 2015-09-29 10:27, Giovanni Piero Deretta wrote:
> There is an ongoing effort to define a subset of C++ which is statically
> checkable as memory safe. In particular the CppCoreGuidelines ban the use
> of static_cast for down casting.
>
> One common use of static_cast is for the CRTP pattern:
>
> template<class Derived> struct Base
> {
> void foo() {
> ...
> static_cast<Derived*>(this)->bar();
> }
> };
As noted in the inline classes thread¹, CRTP in general could use some
love. What I'd *really* prefer is a way to declare a CRTP class such
that 'this' is *implicitly* converted to the derived type on any use.
That is, name lookup is delayed until the derived type is known. IOW,
this would work:
/* new syntax */ Base
{
int foo()
{
return /*this->*/bar(); // note: no member 'bar' in Base
}
};
class Foo : Base // note: class type not repeated
{
int bar() { return 1; }
};
Foo f;
auto i = f.foo(); // Calls Foo::bar
assert(i == 1);
Now you just don't need to cast at all (not explicitly, anyway; the
compiler does it for you). Naturally, the compiler would also enforce
correct usage... which is *also* harder to screw up in the first place
because you aren't repeating the class name any more.
There is room for debate if derived members should be preferred always
over base members, or only if qualified, and if a qualified call shall
be an error if the derived class has no such member. (And of course
other syntax questions that I didn't even attempt to suggest.) I think
this would be far more useful than a mere attribute, however. Ideally,
we would be able to kill off CRTP entirely... not the concept, but in
the sense that it is "CRTP".
(¹
https://groups.google.com/a/isocpp.org/d/msg/std-proposals/u35GIuJECcQ/mtjuTF8ECAAJ)
--
Matthew