ezegoing
ezegoing

Reputation: 526

Declare class member variables inside class member functions

Is there any technique or compiler extension keyword to declare class member variables inside class member functions? Something like

struct test_t{
    void operator ()(){
        instance_local int i = 0;
    }
};

The best that came in my mind was using thread_local and then executing the member function inside another thread, but this would be too ugly to be useful.


EDIT: example

Well I'm really sorry for the following probably confusing example (it is related to my question yesterday Is there any problem in jumping into if(false) block?). I really tried to make a less confusing up...

#include <iostream>

#define instance_local thread_local

struct A{
    A(int i) :
        i(i)
    {

    }
    void dosomethinguseful(){
        std::cout << i << std::endl;
    }
    int i;
};
struct task1{
    int part;
    task1() : part(0){}
    void operator ()(){
        int result_of_calculation;
        switch (part) {
        case 0:{
            //DO SOME CALCULATION
            result_of_calculation = 5;
            instance_local A a(result_of_calculation);
            if(false) 
              case 1:{ a.dosomethinguseful();}
            part++;
        }
        default:
            break;
        }
    }
};
int main(){
    task1 t;
    t();
    t();
    return 0;
}

instance_local A a(result_of_calculation); that is what i could get from such a keyword instead of making a smart pointer for a.

Upvotes: 0

Views: 125

Answers (3)

Guillaume Racicot
Guillaume Racicot

Reputation: 41770

You're describing a coroutine. Here a rough draft of what it could look like (I'm not an expert in coroutine)

auto task1() -> some_awaitable_type {
    result_of_calculation = 5;
    A a(result_of_calculation);

    co_yield;

    a.dosomethinguseful();
}

This could be called like this:

some_awaitable_type maybe_do_something = task1();
// calculation done here

// dosomethinguseful called here
co_await maybe_do_something();

Upvotes: 1

parktomatomi
parktomatomi

Reputation: 4079

There is not. The compiler needs to know the structure of the class without compiling all the method implementations. If you could slip instance_local int foo into a method body, that would make the size of the data structure 4 bytes larger.

On a more principled level, it's not good to hide data. The equivalent feature for global variables that you might be thinking of, static local variables, is a carryover from C that is widely considered to be an anti-pattern: Why are static variables considered evil?

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Not directly, no.

You could define a:

static std::map<test_t*, int> is;

…where the first part of each element is a this pointer.

But, why?

Make a member variable.

Upvotes: 0

Related Questions