c++ - How to do the conditional variable initialization at compiler time? -


c++11 standard have std::conditional<> template type selection boolean condition @ compiler time. how same operation select init value variable initialization? similar type = (exp) ? first_value : second_value;.

i use template:

template<bool b, typename t> inline constexpr t&& conditional_initialize(t&& i1, t&& i2) {     return b ? std::move(i1) : std::move(i2); } 

but can used pod types: int = conditional_initialize<true>(1, 2);. array initialization template compiled error. wrong compile example: int a[] = conditional_initialize<true>({1, 2}, {3,4,5});

error message: no matching function call 'conditional_initialize(<brace-enclosed initializer list>, <brace-enclosed initializer list>)';

who can me template?

template<class t, std::size_t n, std::size_t m, bool b> std::array<t, b?n:m> conditional_array( std::array<t, n>&& lhs, std::array<t, m>&& rhs ) {   return std::move(std::get<b?0:1>( std::tie(lhs, rhs) ) ); } 

this gives you:

auto = conditional_array<int,2,3,true>({{1, 2}}, {{3,4,5}}); 

which close.

in general, {} constructs not expressions, cannot forwarded through mechanism through variable.

we can get:

auto = cond_init<true>( make_array(1,2), make_array(3,4,5) ); 

with bit more work.

template<bool test, class a, class b> std::conditional_t<test,a,b> cond_init(a a, b b) {   return std::move( std::get<test?0:1>( std::tie(a,b) ) ); } template<class t0, class...ts> std::array< std::decay_t<t0>, sizeof...(ts)+1 > make_array( t0&& t0, ts&&...ts ) {   return {{std::forward<t0>(t0), std::forward<ts>(ts)...}}; } 

i didn't make these constexpr, because lazy.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -