Skip to content

Instantly share code, notes, and snippets.

@tahsinkose
Created August 10, 2018 17:01
Show Gist options
  • Save tahsinkose/d5933e1692d40868d7c9a88dcb7a7d17 to your computer and use it in GitHub Desktop.
Save tahsinkose/d5933e1692d40868d7c9a88dcb7a7d17 to your computer and use it in GitHub Desktop.
/*
Compile-time resolution of correct data type based on the platform differency. For example, if the code is compiled in a 32-bit machine,
integral_ptr_t is resolved into uint32_t. Reinterpreting the pointer, which is a void pointer, into uint32_t and dereferencing later back to, e.g. int*,
is a thorough valid operation. -> Refer to https://en.cppreference.com/w/cpp/language/reinterpret_cast for further information.
Reference: https://en.wikibooks.org/wiki/C%2B%2B_Programming/Templates/Template_Meta-Programming
*/
#include <iostream>
#include <cstdint>
template <bool Condition,typename TrueResult, typename FalseResult>
class if_;
template <typename TrueResult,typename FalseResult>
struct if_<true,TrueResult,FalseResult>
{
typedef TrueResult result;
};
template<typename TrueResult,typename FalseResult>
struct if_<false,TrueResult,FalseResult>
{
typedef FalseResult result;
};
int main(){
typename if_<true,int,void*>::result number(3);
typename if_<false,int,void*>::result pointer(&number);
typedef typename if_<(sizeof(void *) > sizeof(uint32_t)),uint64_t,uint32_t>::result integral_ptr_t;
integral_ptr_t converted_pointer = reinterpret_cast<integral_ptr_t>(pointer);
std::cout<<*((int *)converted_pointer)<<std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment