在编译时获取变量名的标准方法 [英] A standard way for getting variable name at compile time

查看:78
本文介绍了在编译时获取变量名的标准方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11或更高版本中是否有某种方式可以实现与以下类似的行为:

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

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

结果应为:

some_int

some_int

如果没有,是否有特定于编译器的方法?我的目标是MSVS.

If not, is there a compiler specific way to do it? I am targeting MSVS.

推荐答案

您问:

在C ++ 11或更高版本中是否有某种方式可以实现与以下类似的行为:

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

int some_int;
std::string x=type_name<some_int>::value; //Theoretical code 
std::cout << x;

结果应为:

some_int

some_int

是的,您可以只使用预处理程序的 stringizing运算符 #:

Yes, you can just use the preprocessor's stringizing operator #:

#include <iostream>

#define NAME_OF( v ) #v

using namespace std;
auto main() -> int
{
    int some_int;
     //std::string x=type_name<some_int>::value; //Theoretical code 
    auto x = NAME_OF( some_int );
    (void) some_int;
    cout << x << endl;
}

如果您要提供其他不同的内容,请发布一个新问题,因为该问题现已得到解答(修改该问题将使该答案无效).

If you're asking for something different, then please post a new question since this one has now been answered (amending the question would invalidate this answer).

作为现实世界用法的示例,以下是将变量及其名称传递给测试函数的宏:

As an example real world usage, here's macro to pass a variable and its name to a test function:

#define TEST( v ) test( v, #v )


如果您要编译时检查,该名称是变量或类型名称,则可以简单地应用 sizeof ,例如以逗号表示:


If you want a compile time check that the name in question is a variable or type name, then you can simply apply sizeof, e.g. in a comma expression:

#define NAME_OF( v ) (sizeof(v), #v)

是否具有 sizeof 的区别在于,是否保证仅在编译时完成此操作,而可能生成的代码也可以在运行时执行某些操作.

The difference between having sizeof or not, is whether this is guaranteed to be done purely at compile time, versus possibly generating code to also do something at run time.

为避免可能的警告,您可以向 void 中添加伪广播:

To avoid a possible warning you can add a pseudo-cast to void:

#define NAME_OF( v ) ((void) sizeof(v), #v)

要使此功能也适用于函数名,可以添加 typeid :

And to make this work also for a function name you can add a typeid:

#define NAME_OF( name ) ((void) sizeof(typeid(name)), #name)

完整示例:

#include <typeinfo>

#define NAME_OF( name ) ((void) sizeof(typeid(name)), #name)

void foo() {}

#include <iostream>
using namespace std;
auto main() -> int
{
    int some_int;
    (void) some_int;
     //std::string x=type_name<some_int>::value; //Theoretical code 
    auto v = NAME_OF( some_int );
    auto t = NAME_OF( int );
    auto f = NAME_OF( foo );
    #ifdef TEST_CHECKING
        (void) NAME_OF( not_defined );
    #endif
    cout << v << ' ' << t << ' ' << f << endl;
}

但是,检查并不是100%完美的,因为仍然可以将函数调用传递给 NAME_OF 宏.

The checking is not 100% perfect, though, because it's still possible to pass a function invocation to the NAME_OF macro.

这篇关于在编译时获取变量名的标准方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆