Default Positional Arguments in C ++ 11 Templates

This allowed you to leave the template arguments empty (using <>), as if you left an empty position argument or redid it to achieve the same effect.

template <int i = 0, int j = 1, int k = 2> void blah() { std::cout << i << " " << j << " " << k << std::endl; } int main() { blah(); // ok blah<>(); // ok blah<1>(); // ok, i = 1 blah<1,,3>(); // not ok, i = 1, j = 1 (default), k = 3 return 0; } 
+6
source share
2 answers

This is impossible to do. You must pass it on.

Here is a suggestion:

 auto constexpr default_j = 1; template <int i = 0, int j = default_j, int k = 2> void blah() { std::cout << i << " " << j << " " << k << std::endl; } int main() { blah(); // ok blah<>(); // ok blah<1>(); // ok, i = 0 blah<1, default_j, 3>(); // ok, explicit and without duplicate magic numbers! return 0; } 
+11
source

Fun with macros (don't try this at home, kids):

 #include <iostream> template <int i = 0, int j = 1, int k = 2> void blah() { std::cout << i << " " << j << " " << k << std::endl; } #define _blah(D, V) (*#V ? V + 0 : D) #define blah_3(I,J,K) blah<_blah(0,I), _blah(1,J), _blah(2,K)>() #define blah_2(I,J) blah_3(I,J,) #define blah_1(I) blah_3(I,,) #define blah__(_1,_2,_3,X,...) blah ## X #define blah(...) blah__(__VA_ARGS__,_3,_2,_1)(__VA_ARGS__) int main() { blah(); blah(, ,); blah(1); blah(1,,); blah(1, ,3); return 0; } 
+7
source

Source: https://habr.com/ru/post/972636/


All Articles