c++ - 我怎样才能有一个受约束的运算符模板?
问题描述
我正在尝试使我的类可转换为任何枚举类型。
enum dst_1 { /*...*/ };
enum dst_2 { /*...*/ };
class src { /*...*/ };
src s;
dst_1 d1 = s;
dst_2 d2 = s;
我不想为每个枚举类型手动添加转换,因此以下不是可接受的解决方案:
// OK, but tedious - you must consider each enum type
class src
{
public:
operator dst_1() const { /*...*/ }
operator dst_2() const { /*...*/ }
// ...
};
不能推导出模板参数使转换成为模板不起作用:
// NOT OK: T cannot be deduced
class src
{
public:
template< typename T > using Enum = enable_if_t< is_enum_v< T >, T >;
template< typename T > operator Enum< T >() const { /*...*/ }
};
我能找到的唯一解决方案是可变参数模板,但我不喜欢它,因为它会强制用户指定计划使用的枚举:
// ALMOST OK, but still tedious - you must know in advance what enums will be used
src< dst_1, dst_2 > s;
dst_1 d1 = s;
dst_2 d2 = s;
那么,有没有更好的解决方案?理想情况下,我想写:
src s;
dst_1 d1 = s;
dst_2 d2 = s;
解决方案
将模板转换为模板不起作用,无法推断出模板参数:
它不能以您所做的方式推断出来,因为T
这里是一个非推断的上下文:
template< typename T > using Enum = enable_if_t< is_enum_v< T >, T >;
This can't be deduced for the same way that this cannot deduce T
:
template <typename T> struct identity { using type = T; }
template <typename T> void foo(typename identity<T>::type);
foo(0); // nope
The correct way to write this operator template is:
template <typename T, std::enable_if_t<std::is_enum_v<T>, int> = 0>
operator T() const;
Or alternatively:
template <typename T, std::enable_if_t<std::is_enum_v<T>, int> = 0> using Enum = T;
template <typename T> operator Enum<T>() const;
Note that the alias has to be T
, not anything else.
推荐阅读
- sql - 有没有办法从 SQL 中的主查询内容中动态选择子查询中的表?
- symfony - api平台,无法使用symfony 4向抽象类添加自定义搜索过滤器
- c# - 我们可以在不创建自定义控件的情况下拦截多个 TextBox 的 KeyPress 事件吗?
- shopify - 如何根据客户标签显示自定义“登录”欢迎消息?(Shopify/液体)
- google-cloud-platform - gcloud beta ai - PERMISSION_DENIED
- vba - 使用可见性属性后,组合框被禁用
- react-native - 样式化的组件是 React Native 的坏习惯?
- angular - Angular 10 - 将 FormControl 数组值转换为用逗号分隔的字符串
- r - 当我使用 xts 包将数据框转换为时间序列数据时,数字和整数变量在 R 中被更改为字符变量
- javascript - 无法在我的 express.js 服务器中使用 Number() 函数 - RangeError