A function that accepts only known compile-time expressions?

Temporary compilation expressions are good because you can use them to specialize templates. For example, tuples can be obtained using a compile-time expression using the std::get method.

 std::cout << std::get<0>(my_tuple) << std::endl; 

Now this expression is pretty ugly. I myself try to develop some kind of tuples (hoping to make them turn them into compilation dictionaries), so, say, they expose the method in the form:

 my_dict.get<0>(); 

Now, what I would like to do is replace it with the [] operator. I was wondering if this is possible at all. First of all, I would not know how to select only constants, compile the expressions known by time as parameters for my operator. Moreover, the return type will depend on the value of the constant expression.

With the definition, however, I can get closer to what I want, with something like

 #define item(x) get<x>() 

so that then i can use

 my_dict.item(0) 

Is there a way to get something better than this?

+6
source share
1 answer

This approach uses types to pass the index, which are then passed to the operator[] , which retrieves the index.

 template<std::size_t n> using idx_t=std::integral_constant<std::size_t, n>; template<std::size_t n> idx_t<n> idx; constexpr int square( int x ) { return x*x; } constexpr int power( int base, size_t pow ) { return (pow==0)?1: (pow==1)?base: ( square(power(base, pow/2)) *( (pow%2)?base:1 ) ); } template<char... cs> struct helper:idx_t<0>{}; template<char c0, char...cs> struct helper<c0, cs...>:idx_t< (c0-'0') * power(10, sizeof...(cs)) + helper<cs...>{} > {}; template<char...cs> constexpr idx_t< helper<cs...>{} > operator""_idx() { return {}; } struct foo { template<std::size_t n> void operator[](idx_t<n>) const { char arr[n]; std::cout << sizeof(arr) << '\n'; } }; 

There are 3 (equivalent, up to syntactic sugar) methods:

 foo f; f[idx_t<1>{}]; f[idx<2>]; f[3_idx]; f[1337_idx]; 

living example . Support 0xff_idx etc. Remains as an exercise.

+2
source

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


All Articles