Ajay Ajay - 26 days ago 16
C++ Question

Template function with 32-bit/64-bit integer overloads

The actual function

bar
is supposed to read from file, where data is written in exactly 4 bytes or 8 bytes (
unsigned int
-
DWORD
or
DWORD64
)

void bar(DWORD64&);
void bar(DWORD&);

template<typename IntType>
void foo(IntType& out)
{
bar(out);
}

int main()
{
int a;
foo(a); // Caller doesn't care
}


Since the caller can pass any integer type (
int
,
LONG
,
DWORD
,
LONGLONG
or anything) - I want a technique so that
foo
may make a call to 32-bit
bar
or 64-bit
bar
.

In short, it would be like:

template<typename IntType>
void foo(IntType& out)
{
if(sizeof(out)==sizeof(DWORD)) // 32-bit
{
DWORD data;
bar(data); // call DWORD version
out = (IntType)data; // Ignore truncation etc.
}
else
{
DWORD64 data;
bar(data); // call DWORD64 version
out = (IntType)data; // Ignore truncation etc.
}
}


Obviously, I want the "if" part to be resolved at compile time.
std::enable_if
or something?

Answer

You could use std::conditional to only differ for sizeof(DWORD) and sizeof(DWORD64) (since you want to support more than just those 2 types):

template<typename IntType>
void foo(IntType& out)
{
  typedef typename std::conditional<sizeof(IntType) == sizeof(DWORD), DWORD, DWORD64>::type RetType;
  RetType data;
  bar(data);
  out = static_cast<IntType>(data);
}
Comments