A standard way for getting variable name at compile time

后端 未结 3 754
情话喂你
情话喂你 2021-02-15 14:13

Is there some way in C++11 or higher to achieve a similar behavior to:

int some_int;
std::string x=variable_name::value; //Theoretical code 
std:         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-02-15 15:07

    As follows from the comments, you need it for passing into a function both the value of the variable and its name. This must be done with the help of a macro:

    #include 
    
    template
    void foo(T var, const char* varname)
    {
        std::cout << varname << "=" << var << std::endl;
    }
    
    #define FOO(var) foo(var, #var)
    
    int main()
    {
        int i = 123;
        double d = 45.67;
        std::string s = "qwerty";
    
        FOO(i);
        FOO(d);
        FOO(s);
        return 0;
    }
    

    Output:

    i=123
    d=45.67
    s=qwerty
    

提交回复
热议问题