ManiAm
ManiAm

Reputation: 1851

Sending Array Pointer/Reference to Template

I wrote a simple program that sends array array[] to a function named ARRAY_MAN, which then modifies the array's contents:

#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;
}

This compiles and runs. But if I replace the line marked (*) with this line:

int *array = new int(3);

I get this error:

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

How can I send this second array to the ARRAY_MAN function?

Upvotes: 3

Views: 112

Answers (1)

einpoklum
einpoklum

Reputation: 132128

Just read the compiler error message:

$ 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);

The second parameter to your function is a reference to fixed-length array, not a reference to a pointer. If your function parameter were a T[], T[N] or T*, that would all (AFAICR) amount to the same thing - taking a pointer. But fixed-length-array references are special. See also:

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

You could say that this is a way to get past the backwards compatibility with C, and have "bona fide" array parameters to functions.

Upvotes: 2

Related Questions