[英]Template function with 32-bit/64-bit integer overloads
实际的功能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(DWORD64)
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
分配时。
您可以使用std::conditional
来选择类型:
template<typename IntType>
void foo(IntType& out){
using dword_t = typename std::conditional<sizeof(IntType) == sizeof(DWORD), DWORD, DWORD64>::type;
dword_t data;
bar(data);
out = (IntType)data;
}
来吧C ++ 17你可以使用constexpr if
,但我不确定这种方法是否实际上更具可读性:
template<typename IntType>
void foo(IntType& out)
{
if constexpr(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.
}
}
问题是,如果你传递了一个int16_t
,你想签名扩展,零填充还是错误?
IMO正确的做法是错误,所以这里有一个模板特化的解决方案:
template <typename IntType>
void foo ( IntType * out ) = delete;
template <>
void foo ( uint64_t * out ) { bar ( * (DWORD64 *) out ); }
template <>
void foo ( int64_t * out ) { bar ( * (DWORD64 *) out ); }
template <>
void foo ( uint32_t * out ) { bar ( * (DWORD *) out ); }
template <>
void foo ( int32_t * out ) { bar ( * (DWORD *) out ); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.