#include <stdio.h>
#include <iostream>
using namespace std;
template <typename T, int N>
int ReturnArraySize(T (&arg1)[N]) {
return N;
}
constexpr int ReturnTheSum(int arg1, int arg2) {
return arg1 + arg2;
}
int main(int argc, char **argv)
{
int arr1[20];
int arr2[ReturnArraySize(arr1)];
int arr3[ReturnTheSum(ReturnArraySize(arr1), ReturnArraySize(arr2))];
return 0;
}
When I compile the code, I get the following error:
/root/Documents/C++11_Fundamentals/ConstExprRelatedFunc/main.cpp:19:67: error: no matching function for call to '
ReturnArraySize(int [(<anonymous> + 1)])'
Piotr Skotnicki
48.8k7 gold badges122 silver badges167 bronze badges
-
I want to know the reason why this error is comingskverma– skverma2016年03月31日 15:35:50 +00:00Commented Mar 31, 2016 at 15:35
1 Answer 1
Because ReturnArraySize is not marked as a constexpr function, arr2 becomes a VLA (variable-length array, a GCC extension, not part of the C++ standard), which cannot be queried for its size at compile time (i.e., deduced by a function template).
You can fix this by making ReturnArraySize a constexpr:
template <typename T, int N>
constexpr int ReturnArraySize(T (&arg1)[N]) {
//~~~~~~^
return N;
}
answered Mar 31, 2016 at 15:50
Piotr Skotnicki
48.8k7 gold badges122 silver badges167 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
skverma
Thanks my issue got fixed
lang-cpp