简体   繁体   中英

How to const map variables

I have three variables int a,b,c which I use to select a value of a fourth variable d.

A short boolean example:

a=0, b=0, c=0 -> d=0
a=0, b=0, c=1 -> d=1
a=0, b=1, c=0 -> d=2
a=0, b=1, c=1 -> d=1
and so on...

I thought about creating a constexpr matrix to create the mapping. The down side is the it generates non readable code. Is there a better option? Maybe some boost library or a known design pattern?

I am programming in c++11

Thank you :)

If you can supply a , b , and c as template arguments, rather than function parameters, you could define a template with three bool arguments, and then supply explicit implementations for the combinations of interest, like this:

template<bool A, bool B, bool C> constexpr int index() { return -1; }
// Truth table
template<> constexpr int index< true, false,  true>() { return 9; }
template<> constexpr int index< true, false, false>() { return 24; }
...

Here is how you would invoke these functions:

cout << index<true,false,true>() << endl; // Prints 9

Demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM