有什么办法将decltype转换为字符串在宏? [英] Is there any way to convert decltype to string in a macro?
问题描述
有什么方法可以在C ++宏中评价 decltype
吗?我的主要动机是创建一个宏,它能够确定这个
的类型并将其转换为字符串。
如果不可能使用 decltype
是否有任何其他方式在类声明中使用的宏可以获得类的类型作为字符串?
decltype
在 C ++宏? 否,因为宏之前是 decltype
。
据我所知,没有办法获得类的名称作为宏,全停。
但是,你可以使用 typeid
获取标记名(严格来说,是一个实现定义的表示),然后使用特定于编译器的工具从中检索出解析名。
例如,GCC提供 demangling库来执行此操作。 / p>
这是一个最小的例子 在线演示
:
#define THIS_CLASS_NAME()demangled(typeid(* this).name())
std :: string demangled(char const * tname){
std :: unique_ptr< char,void *)(void *)>
name {abi :: __ cxa_demangle(tname,0,0,nullptr),std :: free};
return {name.get()};
}
用法:
namespace foo {
template< typename T>
struct bar {
bar(){std :: cout<< THIS_CLASS_NAME()<< '\\\
'; }
};
}
int main(){
foo :: bar< int> b;
}
产量:
<$ $ p>
foo :: bar< int>
Is there any way I can evaluate decltype
in a C++ macro? My main motivation is to create a macro that is able to determine the type of this
and convert it to a string.
If it's not possible to use decltype
is there any other way a macro used inside a class declaration can get the type of the class as a string?
Is there any way I can evaluate
decltype
in a C++ macro?
No, since macros are strictly evaluated before decltype
.
As far as I know there is no way to get the name of the class as a macro, full stop. Any such way would have to be supported by a compiler-generated macro.
However, you can use typeid
to get the mangled name (strictly speaking, an implementation-defined representation), and then use compiler-specific tools to retrieve the demangled name from that.
For instance, GCC offers the demangling library to do this.
Here’s a minimal example online demo
:
#define THIS_CLASS_NAME() demangled(typeid(*this).name())
std::string demangled(char const* tname) {
std::unique_ptr<char, void(*)(void*)>
name{abi::__cxa_demangle(tname, 0, 0, nullptr), std::free};
return {name.get()};
}
Usage:
namespace foo {
template <typename T>
struct bar {
bar() { std::cout << THIS_CLASS_NAME() << '\n'; }
};
}
int main() {
foo::bar<int> b;
}
Yields:
foo::bar<int>
这篇关于有什么办法将decltype转换为字符串在宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!