2017-08-09 74 views
3

我写了一个简单的程序,将阵列array[]到名为ARRAY_MAN功能,然后修改数组的内容:发送数组指针/参考模板

#include <vector> 
#include <iostream> 

template <class Var, class T, std::size_t N, class... Args> 
void ARRAY_MAN(Var variable, T(&)[N], uint32_t numParams, Args... args) 
{ 
    std::vector<T> arguments{args...}; 

    if(arguments.size() != numParams) 
     throw std::runtime_error("mismatch"); 

    for(uint32_t i = 0; i < numParams; ++i) 
     variable[i] = arguments[i]; 
} 


int main(int argc, char* argv[]) 
{ 
    int array[] = {1,2,3}; // (*) 

    // print array before sending 
    for(uint32_t i = 0; i < 3; ++i) 
     std::cout << array[i] << " "; 
    std::cout << std::endl; 

    ARRAY_MAN(array, array, 3, 34, 56, 10); 

    // print array after sending 
    for(uint32_t i = 0; i < 3; ++i) 
     std::cout << array[i] << " "; 
    std::cout << std::endl; 

    return 0; 
} 

这编译和运行。但是,如果我更换行标(*)这一行:

int *array = new int(3); 

我得到这个错误:

no matching function for call to ‘ARRAY_MAN(int*&, int*&, int, int, int, int)’

如何发送本次array到ARRAY_MAN功能?

+3

int * array = ...中的'array'是一个指针,而不是一个数组。你的函数需要一个数组。 – juanchopanza

回答

2

刚刚看完编译错误消息:

$ g++ --std=c++14 -o a a.cpp 
a.cpp: In function ‘int main(int, char**)’: 
a.cpp:26:42: error: no matching function for call to ‘ARRAY_MAN(int*&, int*&, int, int, int, int)’ 
    ARRAY_MAN(array, array, 3, 34, 56, 10); 
             ^
a.cpp:5:6: note: candidate: template<class Var, class T, long unsigned int N, class ... Args> void ARRAY_MAN(Var, T (&)[N], uint32_t, Args ...) 
void ARRAY_MAN(Var variable, T(&)[N], uint32_t numParams, Args... args) 
    ^
a.cpp:5:6: note: template argument deduction/substitution failed: 
a.cpp:26:42: note: mismatched types ‘T [N]’ and ‘int*’ 
    ARRAY_MAN(array, array, 3, 34, 56, 10); 

的第二个参数的功能是将固定长度的数组的引用,而不是一个指针的引用。如果你的函数参数是T[],T[N]T*,那么所有的(AFAICR)就是一样的东西 - 拿一个指针。但定长阵列参考文献是特殊的。另请参见:

What is useful about a reference-to-array parameter?

你可以说这是一种方式来获得过去与C向后兼容,并具有“真正的”数组函数的参数。