Aja*_*jay 2 c++ templates overloading c++11
实际函数bar应该从文件读取,其中数据以4字节或8字节(unsigned int- DWORD或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
}
因为主叫方可以通过任何整数类型(int,LONG,DWORD,LONGLONG或任何东西) -我希望的技术,使得foo可向32位的呼叫bar或64位bar.
简而言之,就像:
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.
       }
 }
显然,我希望在编译时解决" if "部分.std::enable_if或者其他的东西?
你可以使用std::conditional只有不同的sizeof(DWORD)和sizeof(DWORD64)(因为你想支持的不仅仅是那两种类型):
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);
}
Soltuion 1:SFINAE和std::enable_if:
template<typename IntType, typename std::enable_if<sizeof(IntType) == 4>::type* = nullptr>
void foo(IntType& out)
{
    DWORD arg = out;
    bar(arg);
    out = arg;
}
template<typename IntType, typename std::enable_if<sizeof(IntType) == 8>::type* = nullptr>
void foo(IntType& out)
{
    DWORD64 arg = out;
    bar(arg);
    out = arg;
}
Soltuion 2:代表级和部分专业化:
template<typename IntType>
void foo(IntType& out)
{
    foo_helper<IntType>::call(out);
}
template <class IntType, std::size_t Size = sizeof(IntType)>
struct foo_helper;
template <class IntType>
struct foo_helper<IntType, 4>
{
  static void call(IntType &out)
  {
    DWORD arg = out;
    bar(arg);
    out = arg;
  }
};
template <class IntType>
struct foo_helper<IntType, 8>
{
  static void call(IntType &out)
  {
    DWORD64 arg = out;
    bar(arg);
    out = arg;
  }
};
两种溶液都可以static_cast加入口味,特别是在分配到/来自的时候arg.