Loc Tran
Loc Tran

Reputation: 1180

Could I use std::any with C++17 for pointer to member variable?

I'm studying with std::any https://en.cppreference.com/w/cpp/utility/any. I'm wondering if I can use it for accessing data members or functino member of class. I have a struct:

struct test
{
    int a;
    double b;
}

Then I want a general type that can either test::a or test::b.

 std::any ptr;
 ptr = &test::a;

Now ptr is a pointer to a member a of class test. And if I create a new object of class test. I don't know to set a new value of member a of this object. I tried something like following but it is fail at compiler.

 test t;
 std::any ptr;
 ptr = &test::a;

 // set a value for member a of object t using ptr ??
 t.*(std::any_cast<test::*>(ptr)) = 1;

Upvotes: 1

Views: 956

Answers (1)

AndyG
AndyG

Reputation: 41220

The type of &test::a is int test::*, so you're just missing the int portion:

t.*(std::any_cast<int test::*>(ptr)) = 1;

Demo

Upvotes: 3

Related Questions