C(++)类型名称函数/宏

时间:2013-06-06 16:20:40

标签: c++ c

是否有宏要返回(理想情况下为const char*cont char *const)其参数的类型名称或其中的某些信息?

这是 编译时 ,而不是运行时,因此C ++的typeinfo不会这样做。无论如何,我都使用-fno-rtti

2 个答案:

答案 0 :(得分:2)

没有。

C ++ 11在函数定义中确实有__func__标识符,它生成一个带有函数名的字符串变量。大多数C ++编译器对此都有变化,以便“装饰”函数名称。

答案 1 :(得分:-1)

而不是写

cout<<mysteryMacro(std::string<wchar>);
你可以写

cout<<"std::string<wchar>";

我看到的唯一目的是在模板中获取类型信息,例如:

template<T>
void printT() {
    cout << "T is of type"<<mysteryMacro(T);
}

否则你会自动知道代码。

这可以通过模板专业化来实现。

免责声明:这是未经测试的,只是对应该工作的提示。我不认为这是一个很好的解决方案。我相信你可以将其转换为返回字符串而不是打印。关于你需要什么的更多输入将会很棒。

template<T>
void printT() {
    code that generates compile error, so you see that you have an undefined type
}

template<>
void printT<string>() {
    cout << "you have a <string>";
}

如果您想将模板用于变量,您将依赖于自动模板参数推导,如下所示:

template<>
void printT<string>(T) {
    cout << "you have a <string>";
}

并像这样使用

int x;
printT(x);

虽然我不知道为什么,因为,如上所述,除非你在模板中,你将在编写代码时知道类型,在模板中,类型在模板参数中传达,因此knwon(而不是字符串)和你总是可以写printT<T>()

相关问题