I use some type trait like techniques to wrap the pointer and reference to improve its readability. I use ptr<T>
to represent T*
, and lref<T>
to represent T&
. I wrote codes below.
template <typename T>
struct ptr_impl {
using type = T*;
};
template <typename T>
using ptr = typename ptr_impl<T>::type;
template <typename T>
struct lref_impl {
using type = T&;
};
template <typename T>
using lref = typename lref_impl<T>::type;
It seemed to work fine until I wrote such a function
template <typename T, size_t N>
size_t CalculateArraySize(lref<T[N]>) {
return sizeof(T) * N;
}
I got compiler errors when I tried to pass a parameter like this
int arr[100];
lref<int[100]> p = arr;
CalculateArraySize(p);
Compiler(g++10) output err messages as below.
In function 'int main()':
/testcodes/test.cpp:122:23: error: no matching function for call to 'CalculateArraySize(int [100])'
122 | CalculateArraySize(p);
| ^
/testcodes/test.cpp:115:8: note: candidate: 'template<class T, long unsigned int N> size_t CalculateArraySize(lref<T [N]>)'
115 | size_t CalculateArraySize(lref<T[N]>) {
| ^~~~~~~~~~~~~~~~~~
/testcodes/test.cpp:115:8: note: template argument deduction/substitution failed:
/testcodes/test.cpp:122:23: note: couldn't deduce template parameter 'T'
122 | CalculateArraySize(p);
| ^
and I also try to overload another function without template, it works.
size_t CalculateArraySize(lref<int[100]>) {
return sizeof(int) * 100;
}
So why compiler can not deduce template parameter in such case?