C++ Logo

std-proposals

Advanced search

Re: [std-proposals] decltype can access private and protected

From: Jody Hagins <coachhagins_at_[hidden]>
Date: Sat, 16 Apr 2022 18:51:18 -0400
Sorry, I'm a bit late to the party - don't get to this list very often...

As others said, allowing decltype to ignore access restrictions would severely break many widely used idioms.

However, if you need get the type of a private member, this should work on modern compilers (the idiom works all the way back to C++98 - the auto return type stuff is the only thing that is new).


    auto & calibration(Dog &);
    template <auto X> struct Dog_
    { friend auto & calibration(Dog & dog) { return dog.*X; } };
    template struct Dog_<&Dog::calibration>;
    using Dog_calibration_type = std::remove_reference_t<
        decltype(calibration(std::declval<Dog&>()))>;

    static_assert(std::is_same_v<int[3][2][7], Dog_calibration_type>);




> On Mar 25, 2022, at 1:46 PM, Frederick Virchanza Gotham via Std-Proposals <std-proposals_at_[hidden]> wrote:
>
>
> Normally the behaviour is undefined when you dereference a nullptr, but it's allowed with decltype, for example the following is valid code:
>
> decltype( static_cast<std::string*>(nullptr)->compare("Hello") ) my_var;
>
> ++my_var;
>
> I think decltype should be given another privilege: To get the type of protected/private members, for example:
>
> class Dog {
> private:
> int calibration[3u][2u][7u];
> };
>
> int main(void)
> {
> Dog doggy;
>
> decltype(doggy.calibration) my_array;
> }
>
> This past week I was writing code for an Arduino microcontroller to save POD's to the onboard non-volatile Flash, and I had to edit a class to change a member from protected to public just so that I could use decltype on it. This shouldn't be necessary -- just allow decltype to get the type of anything irrespective of accessibility.
>
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals


Received on 2022-04-16 22:51:21