Zwrot typu 1y CRTP i c ++
Ostatnio grałem z CRTP, gdy natknąłem się na coś, co zaskoczyło mnie, gdy użyłem funkcji c ++ 1y, której typ został wydedukowany. Działa następujący kod:
template<typename Derived>
struct Base
{
auto foo()
{
return static_cast<Derived*>(this)->foo_impl();
}
};
struct Derived:
public Base<Derived>
{
auto foo_impl()
-> int
{
return 0;
}
};
int main()
{
Derived b;
int i = b.foo();
(void)i;
}
Zakładałem, że typ powrotu pochodzi zBase<Derived>::foo
byłdecltype
wyrażenia, ale jeśli zmodyfikuję functiofoo
lubię to:
auto foo()
-> decltype(static_cast<Derived*>(this)->foo_impl())
{
return static_cast<Derived*>(this)->foo_impl();
}
Ten kod już nie działa, otrzymuję następujący błąd (z GCC 4.8.1):
||In instantiation of 'struct Base<Derived>':|
|required from here|
|error: invalid static_cast from type 'Base<Derived>* const' to type 'Derived*'|
||In function 'int main()':|
|error: 'struct Derived' has no member named 'foo'|
Moje pytania to: Dlaczego to nie działa? Co mogłabym napisać, aby uzyskać poprawny typ zwrotu bez polegania na automatycznym odliczaniu typu zwrotu?
I cóż ... tutaj jestprzykład na żywo.