vit*_*aut -2 c++ templates overloading
假设我想定义一组函数,每个函数有4个重载,第一个重载采用单个参数类型int32_t,第二个采用int64_t第三个 - uint32_t第四个 - uint64_t.对于每个函数,所有重载都具有相同的实现,因此我可以定义一个函数模板:
template <typename T>
void f(T t) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
然而,这与四次重载不同,因为现在我有一个可用于实例化的每个(整数)类型的单独函数f.但是,实现细节f可能不适用于其他整数类型.为了解决这个问题,我可以将函数模板包装在四个重载函数中:
template <typename T>
void f_impl(T t) {
// ...
}
void f(int32_t value) { f_impl(value); }
void f(int64_t value) { f_impl(value); }
void f(uint32_t value) { f_impl(value); }
void f(uint64_t value) { f_impl(value); }
Run Code Online (Sandbox Code Playgroud)
它工作但每个函数需要大量代码(4个函数重载+ 1个函数模板).有没有办法简化这个?
为了澄清,这是不可取的直接使用模板,因为它没有任何意义(实施的原因或其他方式)有其特比其他类型的int32_t,int64_t,uint32_t和uint64_t.
我已经尝试过使用std::enable_if了,这个例子最好地说明了它的问题:
#include <type_traits>
#include <iostream>
template <typename T>
struct is_supported_int {
static const bool value = false;
};
template <>
struct is_supported_int<int32_t> {
static const bool value = true;
};
template <>
struct is_supported_int<int64_t> {
static const bool value = true;
};
// ...
template <typename T, typename = typename std::enable_if<is_supported_int<T>::value, T>::type>
void f(T t) {
// ...
}
int main() {
short s = 42;
f(s);
}
Run Code Online (Sandbox Code Playgroud)
与我试图模拟的具有重载的原始版本不同,此示例将不会编译,因为f将从匹配函数集中排除short.
不幸的std::is_integral<T>是,Rapptz建议也没有帮助,因为由于实现,f此函数的详细信息只能针对特定类型定义,而不是针对所有整数类型.
像这样的东西会起作用.
#include <type_traits>
#include <iostream>
template<typename T, typename = typename std::enable_if<std::is_integral<T>::value, T>::type>
void f(T t) {
std::cout << "int types only!\n";
}
int main() {
f(1.234f);
f(12);
}
Run Code Online (Sandbox Code Playgroud)
f(1.234f)将无法编译,但f(12)将无法编译.
| 归档时间: |
|
| 查看次数: |
409 次 |
| 最近记录: |