C++ template parameter inference -


as exercise trying write array implementation using templates, function pointer template parameter. function called every time array gets indexed.

template<typename t, int size> using array_fnindex = void (*)(int index);  template<typename t, int size, typename array_fnindex<t, size> fnindex> struct array {     t data[size];     t& operator[](int index) {         fnindex(index);         return data[index];     } };  // example index function template<typename t, int size> void checkindex(int index) {     assert(index < size); }  int main() {     array<int, 10, checkindex<int, 10>> a; // works     array<int, 10, checkindex<int, 11>> b; // works, not want     array<int, 10, checkindex> c; // doesn't work, want     return 0; } 

the last array declaration in main function like, template parameters of checkindex match previous template parameters in array. doesn't compile (using microsoft compiler). following error:

error c2440: 'specialization': cannot convert 'void (__cdecl *)(uint)' 'void (__cdecl *)(uint)' note: none of functions name in scope match target type 

is there way desired result template parameters provided function inferred other parameters?

may not applicable in real use case, suggest callable object containing function check:

template<typename t, int size, typename fnindex> struct array {     t data[size];     t& operator[](int index) {         fnindex{}.template check<size>(index);         return data[index];     } };  struct checkindex {     template<int size>     void check(int index) {         assert(index < size);     }     };  int main() {         array<int, 10, checkindex> c;     return 0; } 

wandbox example


let's analyze fnindex{}.template check<size>(index):

fnindex{} // make temporary object of type `fnindex`     .template check<size>(index) // call `check` method using `size`                                   // template argument , `index`                                  // function argument 

the .template disambiguation syntax required because compiler not know check means - field , line interpreted as:

fnindex{}.check < size > (index)

where < less-than operator, > greater-than operator, , (index) expression.

using .template tells compiler want invoke template method.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -