3

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?

1
  • 3
    the array in int * array = ... is a pointer, not an array. Your function expects an array. Commented Aug 9, 2017 at 21:37

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.