使用标准类型的动态类型信息实例化标识符

Instantiating identifier with dynamic type info on standard types

我知道有更简单的方法可以做到这一点,但这就是我要问的。

假设您有一个模板函数 function1 和另一个模板函数 function2。

函数定义如下:

template <typename A>
void function1(A x) // typename A is part of a class-template function
                    // the typename is declared in the class instantiation
                    // and passed to function2

template <typename B>
void function2(B y) // I know I can use typeinfo(y).name to get name
                    // this returns a const char* 'm' 
                    // 'm' stands for unsigned long on my sytem

'm' 断言的参考在这里:Strange output of std::typeid::name()

正如我所说,我知道可以通过

计算(推导)函数接收的参数
const char* x = typeinfo(parameter).name;
// returns const char* 'm' on my machine

如果一个函数接收一个泛型参数,是否有可能也实例化一个相同类型的新对象。类似于:

<x> foo;
// where x represents the const char* = 'm'
// which in turn is represented by unsigned long on my system
// so foo would be an uninstantiated unsigned long identifier

我看到这里: Creating a new object from dynamic type info 对象不可能,但我想知道内部类型如 int 是否可行。

谢谢!

为此使用模板?

template <typename T> 
void foo(T yourParam)
{
    T newVar;  //Use of the deduced type to declare new variable
}

你也可以使用decltype:

decltype(parameter) newVar;

既然你似乎坚持使用 const char *,而且你问的是内置类型,为什么不使用 switch 语句呢?

switch(x)
{
    case 'm' : {
        unsigned long foo;
        //functionality
        break;
    }
    //other cases
    default : break;
}

您可以使用 decltype 从任何表达式中提取类型,例如使用它来声明另一个变量:

decltype(1 + 3.14159) e;
e = 2.7182818;

但这适用于编译时类型信息("static" 类型)。没有办法基于动态类型来做,也没有办法使用运行时类型数据(typeinfotypeid returns,或者你可以在运行时捕获的任何其他对象)。充其量您可以获取类型名称,写出 C++ 源文件,然后在其上调用 C++ 编译器。