Two Templates, one of which is "unable to deduct"

Hello,

Consider the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <iomanip>
using namespace std;
template<typename T>
T Acceptable(T x)
{
    return x;
}

template<typename T, size_t _x, size_t _y>
bool ensure(T (&arr)[_x][_y], int x)
{
    for(int i = 0; i < _x; ++i)
    {
        for(int j = 0; j < _y; ++j)
        {
            if(arr[i][j] == x)
                return true;
        }
    }
    return false;
}


int main()
{
    cout<<fixed<<setprecision(7);

    cout<<Acceptable(5)<<endl;
    cout<<Acceptable(5.7)<<endl;

    char the_Renaissance[20][30];
    for(int i = 0; i < 20; ++i)
    {
        for(int j = 0; j < 30; ++j)
        {
            the_Renaissance[i][j] = 'c';
        }
    }
    if(ensure(the_Renaissance, 99))
        cout<<"INDEED";
    return 0;
}


As you may have guessed, it works perfectly. The program does not confuse the variables. The opposite happens with the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

template<typename T, size_t W, size_t K>
void detail(T (&arr)[W][K], int p, int q)
{
    arr[p][q] = 220;
}

int main()
{
    unsigned int W, K;
    cin>>W;
    cin>>K;
    int custom[W][K] {};
    for(int i = 0; i < W; ++i)
    {
        for(int j = 0; j < K; ++j)
        {
            detail(custom, i, j);
        }
    }
    return 0;
}


Why is that the case?
Variable-length arrays are not part of C++.
And apparently they don't play well with template deduction.
Last edited on
Templates are instantiated during compilation. The compiler cannot possibly foresee which W and K shall the users give on each run of the program, but one has to generate code for different function for each unique pair of (W,K).

That is similar to automatic arrays; they are defined already during compilation. Variable-length arrays (VLA) have more code to delay the size determiation to the runtime. Support for VLA has been added to C, but not to C++. Some compilers allow VLA in C++ as non-standard extension.

C++ has std::vector that is more than VLA. Your latter program written with vector:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <vector>

int main()
{
    unsigned int W {}, K {};
    std::cin >> W;
    std::cin >> K;
    std::vector<std::vector<int>> custom( W, std::vector<int>( K, 220 ) );
    return 0;
}
Topic archived. No new replies allowed.