我有一节课:
class fileUnstructuredView {
private:
void* view;
public:
operator void*() {
return view;
}
};它可以做到这一点:
void* melon = vldf::fileUnstructuredView();但它不能这样做:
int* bambi = vldf::fileUnstructuredView();
//or
int* bambi = (int*)vldf::fileUnstructuredView();相反,我不得不去做
int* bambi = (int*)(void*)vldf::fileUnstructuredView();或者为int*创建另一个显式类型转换运算符。
重点是,我想轻松地将类转换成各种指针类型,包括所有的基本指针类型和一些pod结构类型。有没有一种方法可以做到这一点,而不为所有它们创建一个转换运算符?与我所能想到的最接近的是ZeroMemory方法,它似乎不需要任何类型的参数。
发布于 2014-07-09 17:15:48
是的,您可以有一个转换函数模板。
template <class T>
operator T*() {
return static_cast<T*>(view);
}发布于 2014-07-09 17:23:14
使用模板允许转换到所有类型,然后使用enable_if只允许对所有类型和基本类型进行转换。
class fileUnstructuredView {
private:
void* view;
public:
template<class T,
class enabled=typename std::enable_if<std::is_pod<T>::value>::type
>
operator T*() { //implicit conversions, so I left the:
return view; //pointer conversion warning
}
template<class T>
T* explicit_cast() { //explicit cast, so we:
return static_cast<T*>(view); //prevent the pointer conversion warning
}
};http://coliru.stacked-crooked.com/a/774925a1fb3e49f5
https://stackoverflow.com/questions/24659851
复制相似问题