Boost logo

Boost :

Subject: Re: [boost] [offtopic] C++11 useful trick
From: Eric Niebler (eric_at_[hidden])
Date: 2012-07-03 03:13:38

On 7/2/2012 7:26 PM, Ravi wrote:
> On Monday, July 02, 2012 12:41:22 PM Eric Niebler wrote:
>>> Use of a C++11 feature just for the sake of it doesn't seem like such a
>>> good idea to me.
>> <baffle> Have I not given enough good reasons above? Maybe I'll just
>> keep my good ideas to myself next time. :-/
> Please don't. This one is actually pretty widely applicable if you are doing
> type deduction in C++11; it took me quite a while to figure this one out when
> I ran into it. I, too, fail to see how the reasons you gave were not perfectly
> clear.

Thanks Ravi. For the record, this trick is also useful for CRTP bases
when you need to static_cast this from base to derived in a return type:

    template<typename Derived>
    struct Base
        template<typename D = Derived>
        auto foo() -> decltype(static_cast<D *>(this)->bar())
            return static_cast<D *>(this)->bar();

    struct Derived : Base<Derived>
        int bar()
            return 0;

    int main()
        Derived d;;

If you try to do this instead:

    auto foo() -> decltype(static_cast<Derived *>(this)->bar())

it won't compile because the compiler can't tell that the static_cast is
legit. You might think this would work:

    auto foo() -> decltype(std::declval<Derived &>().bar())

...but then it can't find member bar() in Derived.

Eric Niebler
BoostPro Computing

Boost list run by bdawes at, gregod at, cpdaniel at, john at