首页 > 解决方案 > 我怎样才能有一个受约束的运算符模板?

问题描述

我正在尝试使我的类可转换为任何枚举类型。

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;

标签: c++c++17

解决方案


将模板转换为模板不起作用,无法推断出模板参数:

它不能以您所做的方式推断出来,因为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.


推荐阅读