converting a variable name to a string in C++

前端 未结 8 987
广开言路
广开言路 2020-12-01 01:15

I\'d like to output some data to a file. For example assume I have two vectors of doubles:

vector data1(10);
vector data2(10); 
         


        
相关标签:
8条回答
  • 2020-12-01 02:08

    For this case I have made nameof() macro. It returns a std::string name of a variable, type or member. It works like nameof() in C#.

    For Example:

    #include "nameof.h"
    
    std::vector<double> data1(10);
    std::string name = nameof(data1); // "data1"
    
    struct Foo1
    {
        struct Foo2
        {
            Foo1* foo1;
        };
    
        Foo1* foo1;
        Foo2 foo2;
    };
    
    name = nameof(Foo1::foo1->foo2.foo1); // "foo1"
    
    name = nameof(123); // std::logic_error exception
    
    0 讨论(0)
  • 2020-12-01 02:10

    You can use the preprocessor, there's a stringify token, but it's only available from the source, not to a function (you'd get the argument name).

    0 讨论(0)
提交回复
热议问题