【发布时间】:2015-08-31 14:24:25
【问题描述】:
为了方便特定类,我定义了一个自定义enum,现在它妨碍了更通用的进程对其进行处理。
我应该如何执行这种类型转换?
// A templated value holder:
template <typename T>
struct Holder {
T _value;
};
// A more general process..
template <typename T>
struct General {
Holder<T> *holder;
};
// ..over integral types:
struct IntGeneral : General<int> {};
// Here is something interesting: I can tell that this process will work on
// any enum type. But I've found no way to make this explicit.
// Convenience for a particular case
typedef enum {One, Two, Three} Enum;
typedef Holder<Enum> Particular;
int main() {
Particular* a( new Particular { One } );
IntGeneral ig { static_cast<Holder<int>*>(a) }; // compiler grumbles
return EXIT_SUCCESS;
}
这是我得到的:
error: invalid static_cast from type ‘Particular* {aka Holder<Enum>*}’ to type ‘Holder<int>*’
有没有办法让我保持方便的Enum 并编译这段代码?
编辑:原来是XY problem。此处已接受 Y 的答案,并讨论了几个。 X 已移至another question。
【问题讨论】:
-
如果
sizeof(Enum) != sizeof(int)你会发生什么? -
@GlennTeitelbaum 非常正确。这就是我宁愿需要
EnumGeneral : General<something_that_would_mean_any_kind_of_enum>之类的东西的原因。有没有办法做到这一点?
标签: c++ templates enums generic-programming concept