我认为这应该很容易,但我已经为此苦苦挣扎了一段时间,所以我想我应该在这里问。
我想制作一个模板元函数,它将对应于 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>
如果不存在,则取消。)