Search code examples
c++variablesc++17

Is there some way to define a variable as a function such that calling the variable at some given time will return the function's output at that time?


Essentially, I'm trying to do something like

#define foobar foo.bar()

But without the use of #define, so I can write something along the lines of

double foobar = foo.bar();

Obviously, compiling the code above will just define foobar as whatever foo.bar() returns at the time of definition. What I want to do is the above in such a way that using foobar at some time in the code will just use whatever foo.bar() returns at that time, and not whatever it was at definition of foobar.


Solution

  • Obviously, compiling the code above will just define foobar as whatever foo.bar() returns at the time of definition. What I want to do is the above in such a way that using foobar at some time in the code will just use whatever foo.bar() returns at that time, and not whatever it was at definition of foobar.

    You want a function not a variable:

    auto foobar() { return foo.bar(); } 
    

    If foo is not a global (i hope so) and you want to declare the callable on the fly just as you can declare a double, you can use a lambda expression:

    Foo foo;
    auto foobar = [&foo](){ return foo.bar(); };
    
    // call it:
    foobar();
    

    To call the function without the function call syntax () you could use a custom type that calls the function when converted to the returned type. However, as this is non-idiomatic obfuscation, I am not going into more details.