/*
Author: Peter R. Bloomfield
Website: avidinsight.uk
Example of using std::conditional<> to select an unsigned integer type based on
size. The size is specified by template parameter.
Note that ideone seems to output abbreviated typenames for typeid().name().
Try the code in an offline compiler to see the correct output.
*/
#include <iostream>
#include <type_traits>
#include <typeinfo>
// A template which selects an unsigned integer type with at least the number of
// bytes specified in the template parameter.
template <std::uint8_t T_numBytes>
using UintSelector =
typename std::conditional<T_numBytes == 1, std::uint8_t,
typename std::conditional<T_numBytes == 2, std::uint16_t,
typename std::conditional<T_numBytes == 3 || T_numBytes == 4, std::uint32_t,
std::uint64_t
>::type
>::type
>::type;
// A test function which uses RTTI to output the type name.
template <std::uint8_t T_numBytes>
void test()
{
std::cout << static_cast<unsigned int>(T_numBytes) << " => " <<
typeid(UintSelector<T_numBytes>).name() << std::endl;
}
int main() {
test<1>();
test<2>();
test<3>();
test<4>();
test<5>();
test<6>();
test<7>();
test<8>();
test<9>();
return 0;
}
LyoKQXV0aG9yOiAgUGV0ZXIgUi4gQmxvb21maWVsZApXZWJzaXRlOiBhdmlkaW5zaWdodC51awoKRXhhbXBsZSBvZiB1c2luZyBzdGQ6OmNvbmRpdGlvbmFsPD4gdG8gc2VsZWN0IGFuIHVuc2lnbmVkIGludGVnZXIgdHlwZSBiYXNlZCBvbgpzaXplLiBUaGUgc2l6ZSBpcyBzcGVjaWZpZWQgYnkgdGVtcGxhdGUgcGFyYW1ldGVyLgoKTm90ZSB0aGF0IGlkZW9uZSBzZWVtcyB0byBvdXRwdXQgYWJicmV2aWF0ZWQgdHlwZW5hbWVzIGZvciB0eXBlaWQoKS5uYW1lKCkuClRyeSB0aGUgY29kZSBpbiBhbiBvZmZsaW5lIGNvbXBpbGVyIHRvIHNlZSB0aGUgY29ycmVjdCBvdXRwdXQuCiovCgojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDx0eXBlX3RyYWl0cz4KI2luY2x1ZGUgPHR5cGVpbmZvPgoKLy8gQSB0ZW1wbGF0ZSB3aGljaC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