c++ - 模板类的部分模板特化,如 std::function
问题描述
我想创建一个函数重载来部分专门化一个模板类。如何使这段代码工作?
template <typename T>
struct Foo;
template <typename Result, typename ... Args>
struct Foo<Result(Args...)>
{
Result Bar()
{
Result t;
return t;
}
};
template <typename ... Args>
void Foo<void(Args...)>::Bar()
{
// do nothing;
}
解决方案
如果它只是一个应该暴露不同行为 if 的单个成员函数Result=void
,那么使用标记调度:
#include <type_traits>
template <typename T>
struct Foo;
template <typename Result, typename... Args>
struct Foo<Result(Args...)>
{
Result Bar()
{
return Bar(std::is_void<Result>{});
}
private:
Result Bar(std::false_type)
{
Result t;
// Do something
return t;
}
void Bar(std::true_type)
{
// Do nothing
}
};
或者,部分专业化整个班级:
template <typename... Args>
struct Foo<void(Args...)>
{
void Bar()
{
// Do nothing
}
};
推荐阅读
- flutter - 在工作区中找不到启动配置“Android”
- flutter - 是否可以在浏览器中打开一个新的空白选项卡?
- c++ - 通过 Windows 上的串行端口解析 2Hz 和更大的 GPS 数据
- javascript - 当有人加入特定频道时发送消息 - Discord Bot
- c# - Unity 向鼠标位置移动有限距离
- angular - fakeAsync 是否定义范围?使用 Jasmine 和 fakeAsync 测试 RXJS 超时
- typescript - Chart.js 3.x 自定义定位器:不能在 TypeScript 中使用它们
- typescript - 如何使用 switchmap、pipe、map 和 catchError 实现通用帮助器来处理错误
- next.js - npm run build 给出错误:图像优化
- r - !all(is.na(df)) 在控制台中返回 FALSE 但通过 if