c++ - A function that accepts only compile time known expressions? -


compile time expressions because can use them specialize templates. example, tuples can accessed using compile time expression std::get method.

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

now, above expression pretty ugly. trying develop sort of tuples myself (hoping make turn them compile time dictionaries), that, say, expose method in form:

my_dict.get<0>(); 

now, substitute [] operator. wondering if possible @ all. first of all, wouldn't know how select constant, compile time known expressions parameters operator. moreover, return type depend on value of constant expression.

with define, however, can closer want like

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

so can use

my_dict.item(0) 

is there way better this?

this approach uses types convey index, passed operator[], extracts 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 3 (equivalent, syntactic sugar) ways use this:

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

live example. support 0xff_idx etc left exercise.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -