c++ - cleaner alternative for conditional typedef using templates -


while playing around templates, remove macros in code, got following code,

typedef std::conditional<sizeof(int) == sizeof(void*),     int,     std::conditional<sizeof(long int) == sizeof(void*),         long int,         std::enable_if<sizeof(long long int) == sizeof(void*), long long int>::type     >::type >::type int; typedef std::conditional<sizeof(unsigned int) == sizeof(int),     unsigned int,     std::conditional<sizeof(unsigned long int) == sizeof(int),         unsigned long int,         std::enable_if<sizeof(unsigned long long int) == sizeof(int), unsigned long long int>::type     >::type >::type uint; 

while trying replace,

#if sizeof(int) == sizeof(void*)     typedef int int;     typedef unsigned int uint; #elif sizeof(long int) == sizeof(void*)     typedef long int int;     typedef unsigned long int uint; #elif sizeof(long long int) == sizeof(void*)     typedef long long int int;     typedef unsigned long long int uint; #else     #error #endif 

can think of cleaner , shorter alternative using templates? or bad idea use templates replace every possible macros.

btw, code used passing integer values c functions accept void*, minimal overhead.

maybe alias you:

using int  = best<int,best<long int,long long>>;  using uint = best<unsigned int,best<unsigned long int,unsigned long long int>>; 

where best template alias, defined as:

template<typename t, typename u> using best = typename std::conditional<sizeof(t)==sizeof(void*),t,u>::type; 

note i'm not sure if solves problem, if complain lengthy templates, maybe above technique gives idea how make bit shorter — and cleaner.

you use _t version if have c++14:

template<typename t, typename u> using best = std::conditional_t<sizeof(t)==sizeof(void*),t,u>; 

hope helps.


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -