c++ - 如何防止用户指定函数模板参数,强制推导它?
问题描述
假设我有一个模板函数:
template <typename A, typename B>
A fancy_cast(B)
{
return {};
}
预期用途类似于fancy_cast<int>(1.f)
.
但是没有什么能阻止用户手动指定第二个模板参数:fancy_cast<int, int>(1.f)
,这会导致问题。
如何防止typename B
被指定并强制推断?
我想出了这个:
// Using this wrapper prevents the code from being
// ill-formed NDR due to [temp.res]/8.3
template <auto V> inline constexpr auto constant_value = V;
template <
typename A,
typename ...Dummy,
typename B,
typename = std::enable_if_t<constant_value<sizeof...(Dummy)> == 0>
>
A fancy_cast(B)
{
return {};
}
它似乎工作,但它非常麻烦。有没有更好的办法?
解决方案
制作fancy_cast
变量模板怎么样?
template <typename A>
struct fancy_cast_t {
template <typename B>
A operator()(B x) const { return x; }
};
template <typename A>
constexpr fancy_cast_t<A> fancy_cast {};
fancy_cast<int>(1.5); // works
fancy_cast<int, int>(1.5); // doesn't work
fancy_cast<int>.operator()<int>(1.5); // works, but no one would do this
推荐阅读
- excel - 当两个不同的列具有特定值时,如何修复此 Excel 公式以便从计算中排除行?
- windows-10 - Autohotkey:最小化窗口的问题
- azure - 如何使用 azure 数据共享在 Azure 数据资源管理器中仅选择特定表作为关注者而不是整个数据库
- python - 您将如何在数据框 groupby 中查找最新日期?
- c++ - C++ unordered_map 奇怪的大小分配
- node.js - NodeJS:obj.values 不是函数
- string - 将字符串分隔到字符堆栈
- pandas - 不需要的列的 Web 抓取问题
- python - Python Pandas read_excel - OverflowError:日期值超出范围
- fix-protocol - QuickFixj Api - 会话 Api - 方法