Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模板:从类型名中获取正确的变量名_C++_Templates - Fatal编程技术网

C++ 模板:从类型名中获取正确的变量名

C++ 模板:从类型名中获取正确的变量名,c++,templates,C++,Templates,比方说,我有4个不同指针类型的数组。 我需要一个模板函数,它将参数存储在适当的数组中。像这样的 int* arr_int[10]; double* arr_double[10]; uint64_t* arr_uint64_t[10]; template <typename T> void add_value (int pos, T value) { //i want to store value in the a

比方说,我有4个不同指针类型的数组。 我需要一个模板函数,它将参数存储在适当的数组中。像这样的

int*            arr_int[10];
double*         arr_double[10];
uint64_t*       arr_uint64_t[10];


template <typename T> 
void add_value (int pos, T value) {
        //i want to store value in the array of it's type
        arr_##(*T)[pos]=value;
        //of course, this does not work :)
}

int main(int argc, char *argv[])
{
        int      a = 2;
        double   b = 4.2;
        uint64_t c = 123456;

        add_value(0,&a);
        add_value(0,&b);
        add_value(0,&c);

        //add more values
        //do something with arrays
        ....

        return 0;
} 
int*arr_int[10];
双倍*arr_双倍[10];
uint64_t*arr_uint64_t[10];
模板
无效添加值(整数位置,T值){
//我想将值存储在其类型的数组中
arr###(*T)[pos]=值;
//当然,这是行不通的:)
}
int main(int argc,char*argv[])
{
INTA=2;
双b=4.2;
uint64_t c=123456;
添加_值(0,&a);
添加值(0,&b);
添加_值(0,&c);
//添加更多值
//对数组做些什么
....
返回0;
} 

有可能吗?

没有,按照您的意思,不可能通过模板生成名称。您可以按照Nick所说的操作—只需创建重载函数,或使用指定类型的静态数组创建模板类:

template <typename T>
struct array_holder
{
    static T * arr[10];
};

template <typename T>
T * array_holder<T>::arr[10];

template <typename T>
void add_value (int pos, T value)
{
    array_holder<T>::arr[pos] = something_you_need;
}
模板
结构数组\u保持器
{
静态T*arr[10];
};
模板
T*数组_holder::arr[10];
模板
无效添加值(整数位置,T值)
{
数组持有者::arr[pos]=您需要的东西;
}

为什么不让重载函数分别使用其中一种类型并将其添加到正确的数组中?