0

我认为这应该很容易,但我已经为此苦苦挣扎了一段时间,所以我想我应该在这里问。

我想制作一个模板元函数,它将对应于 C++11 枚举类的类型作为其参数,并返回一个 int:

  • 如果枚举类E有一个枚举值a,则返回static_cast<int>(E::a)
  • 如果枚举类E没有枚举值a,则返回42

然后我想创建一个模板函数,它接受某个枚举类的运行时实例E,静态将其转换为 int,并检查它是否与此元函数匹配。

我尝试了多次迭代,模板化结构并使用模板部分专业化来尝试区分是否E::a存在,还使用函数模板......我不确定我是否可以重建我尝试过的所有内容,但这是最近的迭代:

template <typename E>
inline int get_a_int_val(int result = E::a) { return result; }

template <typename E>
inline int get_a_int_val(int result = 42) { return result; }

template <typename E>
inline bool is_a_val(const E & input) {
  return static_cast<int>(input) == get_a_int_val<E>();
}

这不起作用,因为我正在重新定义默认参数。

template <typename E, int result = E::a>
inline int get_a_int_val() { return result; }

template <typename E, int result = 42>
inline int get_a_int_val() { return result; }

template <typename E>
inline bool is_a_val(const E & input) {
  return static_cast<int>(input) == get_a_int_val<E>();
}

这不起作用,因为非类型参数不能依赖于类型参数。

template <typename E>
struct get_a_int_val {
  static const int value = 42;
};

template <typename E>
struct get_a_int_val<E> {
  static const int value = static_cast<int>(E::a);
};

template <typename E>
inline bool is_a_val(const E & input) {
  return static_cast<int>(input) == get_a_int_val<E>::value;
}

这不起作用,因为

error: 
  class template partial specialization does not specialize any template
  argument; to define the primary template, remove the template argument
  list

这样做的正确方法是什么?


动机:

我想这样做的原因是,我想解决我在这里报告的似乎是 libstdc++ 中的错误:https ://gcc.gnu.org/bugzilla/show_bug.cgi?id=68307

<system_error>标头中的 C++11 中,有一堆std::errc应该定义的枚举器值,但是,在 mingw 上,它们中的一些丢失了。这会在我的程序中导致编译错误,因为根据Asio配置方式,lib::asio::errc可能会被 typedef 为std::errc,并websocketpp假定这lib::asio::errc::operation_canceled是一个已定义的符号。我想拼凑一些可以在websocketpp代码中放置的垫片,以便在任何平台上都可以接受地定义它(lib::asio::errc::operation_canceled如果存在,或者<cerrno>如果不存在,则取消。)

4

2 回答 2

2

您可以通过多种方式执行此操作,其中之一如下:

template <typename E, typename Enable = void>
struct get_a_int_val {
  static const int value = 42;
};

template <typename E>
struct get_a_int_val<E, typename std::enable_if<std::is_same<decltype(E::a), 
                                                decltype(E::a)>::value, void>::type>{
  static const int value = static_cast<int>(E::a);
};

现场演示

于 2015-11-12T20:12:55.123 回答
1

您可以为此创建一个特征:

template <typename E>
std::false_type has_a_impl(...);

template <typename E> auto has_a_impl(int) -> decltype(E::a, std::true_type{});

template <typename E>
using has_a = decltype(has_a_impl<E>(0));

然后在 SFINAE 中使用它:

template <typename E>
std::enable_if_t<has_a<E>::value, int>
get_a_int_val() { return static_cast<int>(E::a); }

template <typename E>
std::enable_if_t<!has_a<E>::value, int>
get_a_int_val() { return 42; }

演示

于 2015-11-12T19:43:31.510 回答