C++:无法使用类型条件在模板函数中使用类型为'double'的左值初始化'char*'类型的参数

Jay*_*ong 3 c++ arrays templates

我想编写一个模板函数来将数据从一个数组复制到另一个数组.我只想处理int,doublechar*在我的计划(字符串)数组.

template<typename T>
void copy_key(T *destination, int destination_index, T *source, int source_index){
    if (typeid(T) == typeid(int) or typeid(T) == typeid(double)){
        destination[destination_index] = source[source_index];
    } else {
        // char* case
        strcpy(destination[destination_index], source[source_index]);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我copy_key()如下调用,我将收到错误:无法初始化类型为'double'的左值类型'char*'的参数.

int main(int argc, const char * argv[]) {
    double from_array[3] = {1.0,2.0,3.0};
    double to_array[3];
    copy_key(to_array, 0, from_array, 2);
    std::cout << to_array[0] << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想如果Tdouble的话,就不会输入else块.我的问题是如何在我的示例中正确使用模板类型的条件?

eer*_*ika 5

我想如果Tdouble的话,就不会输入else块.

你没想到.但是你对其后果的假设是不正确的.

仅仅因为某些代码不会被执行,并不意味着它与程序的其余部分一起不需要很好地形成.

即使在这种情况下,编译器可能会证明该行不会被执行,但这种证明对于所有可能的程序来说实际上是不可能的,因此它不会影响程序的正确性.

典型的解决方案是使用重载或模板特化:

void copy_key(char *destination, int destination_index, const char *source, int source_index){
    strcpy(...);
}

void copy_key(double *destination, int destination_index, double *source, int source_index){
    destination[destination_index] ...
}
Run Code Online (Sandbox Code Playgroud)

在即将推出的C++ 17中,将constexpr if允许在单个函数中允许有条件编译的块.