简体   繁体   English

将变量名转换为 C++ 中的字符串

[英]converting a variable name to a string in C++

I'd like to output some data to a file.我想将一些数据输出到文件中。 For example assume I have two vectors of doubles:例如假设我有两个双精度向量:

vector<double> data1(10);
vector<double> data2(10); 

is there an easy way to output this to a file so that the first row contains the headings 'data1' and 'data2' followed by the actual contents.有没有一种简单的方法可以将其输出到文件,以便第一行包含标题“data1”和“data2”,后跟实际内容。 The function which outputs the data will be passed various different arrays so hardcoding the name of the heading is not possible - ideally I'd like to convert the variable name to some string and then output that string followed by the contents of the vector array.输出数据的函数将传递各种不同的数组,因此不可能对标题的名称进行硬编码 - 理想情况下,我想将变量名称转换为某个字符串,然后输出该字符串,后跟向量数组的内容。 However, I'm not sure how to convert the variable name 'data1' to a string, or indeed if it can easily be done (from reading the forums my guess is it can't) If this is not possible an alternative might be to use an associative container such as map or perhaps more simply a 'pair' container.但是,我不确定如何将变量名 'data1' 转换为字符串,或者实际上是否可以轻松完成(从阅读论坛我的猜测是它不能)如果这是不可能的,另一种可能是使用关联容器,例如地图或更简单的“配对”容器。

pair<vector<double>,string> data1(10,'data1');  

Any suggestions would be welcome!欢迎大家提出意见!

You can use the preprocessor "stringify" # to do what you want:您可以使用预处理器“stringify” #执行您想要的操作:

#include <stdio.h>

#define PRINTER(name) printer(#name, (name))

void printer(char *name, int value) {
    printf("name: %s\tvalue: %d\n", name, value);
}

int main (int argc, char* argv[]) {
    int foo = 0;
    int bar = 1;

    PRINTER(foo);
    PRINTER(bar);

    return 0;
}


name: foo   value: 0
name: bar   value: 1

(Sorry for printf , I never got the hang of <iostream> . But this should be enough.) (抱歉printf ,我从来没有掌握<iostream> 。但这应该足够了。)

try this:尝试这个:

#define GET_VARIABLE_NAME(Variable) (#Variable)

//in functions //在函数中

int var=0;    
char* var_name= GET_VARIABLE_NAME(var);

I had the same problem.我有同样的问题。 After a little bit of experimentation I created following macros that convert names of variables, fields, functions, methods and types to strings.经过一些实验,我创建了以下宏,将变量、字段、函数、方法和类型的名称转换为字符串。

#define MACRO_VARIABLE_TO_STRING(Variable) (void(Variable),#Variable)

#define MACRO_FUNCTION_TO_STRING(Function) (void(&Function),#Function)

#define MACRO_METHOD_TO_STRING(ClassName,Method) (void(&ClassName::Method),#Method)

#define MACRO_TYPE_TO_STRING(Type) (void(sizeof(Type)),#Type)

The code uses comma operator and void conversion to force compiler to check if variable, function, etc. really exists.代码使用逗号运算符和void 转换来强制编译器检查变量、函数等是否真的存在。 The nice thing is that it works well with uninitialized variables too.好消息是它也适用于未初始化的变量。 I tested it on both VC and GCC with all pedantic options I found out without any warning messages.我在 VC 和 GCC 上使用我发现的所有迂腐选项对其进行了测试,没有任何警告消息。

int GetAndPrintValue(const char* VariableName)
{
   std::cout << VariableName << std::endl;
   return 10;
}

int Variable=GetAndPrintValue(MACRO_VARIABLE_TO_STRING(Variable));

I use such code when I write parsers that reads data from input stream and if parsed variable is out of bounds it throws an exception with name of variable that failed my validity checks.当我编写从输入流读取数据的解析器时,我会使用这样的代码,如果解析的变量超出范围,它会抛出一个异常,其中包含未通过有效性检查的变量名称。

Slightly adapted from @sarnold's answer, for C++:稍微改编自@sarnold 的回答,适用于 C++:

#define DEBUG(x) std::cout << #x << " = " << x << std::endl;

An example program which uses this:一个使用这个的示例程序:

int main() {
    int foo = 1;
    DEBUG(foo);

    return 0;
}

您可以使用预处理器,有一个 stringify 标记,但它只能从源中获得,不能从函数中获得(您将获得参数名称)。

我原以为显而易见的答案是让执行输出的函数将标题文本作为字符串参数。

For this case I have made nameof() macro.对于这种情况,我制作了nameof()宏。 It returns a std::string name of a variable, type or member.它返回一个变量、类型或成员的 std::string 名称。 It works like nameof() in C#.它的工作原理类似于 C# 中的 nameof()。

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

I had a similar quest.我有一个类似的追求。 In Qt, I got tired of constantly writing the variable name as a string without autocomplete when writing to qDebug() .在 Qt 中,我厌倦了在写入qDebug()时不断地将变量名称写为没有自动完成功能的字符串。 After a lot of trial and error with different macros and functions, I found that this macro works great:在对不同的宏和函数进行了大量反复试验后,我发现这个宏效果很好:

#define PRINT(x) ", " << #x << ": " << x

Example usage:用法示例:

int someVariable = 42;
double anotherVariable = 13.37;
qDebug().nospace() << "Some text" << PRINT(someVariable) << PRINT(anotherVariable);

Output:输出:

Some text, someVariable: 42, anotherVariable: 13.37

I guess this (or something very similar) will work for std::cout as well.我想这(或非常相似的东西)也适用于std::cout

A bit late to the party, but I hope this can help anyone out there!聚会有点晚了,但我希望这可以帮助那里的任何人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM