是否有方法为任何指针类型定义转换操作符
Is there a way to define a conversion operator for any pointer type?
我有这样一个类:
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结构类型。有没有一种方法可以做到这一点,而不需要为所有这些操作符创建转换操作符?我能想到的最接近我所要求的是zerommemory方法,它的参数似乎没有任何类型。
是的,你可以有一个转换函数模板。
template <class T>
operator T*() {
return static_cast<T*>(view);
}
使用模板允许所有类型的转换,然后使用enable_if
只允许POD和基本类型的转换。
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 相关文章:
- 仅为某些模板专用化定义转换运算符:预期类型/预期类型说明符
- 模拟返回具有多个用户定义转换的类型的方法
- 是否可以使用明确的模板参数调用模板的用户定义转换操作员
- 使用自定义转换运算符的不明确性
- C++显式积分用户定义转换
- 解决隐藏歧义的不明确用户定义转换
- 如何自定义转换模板参数
- 用户定义转换的第二个标准转换序列
- 如何将串联的定义转换为RC文件中的字符串
- 是否可以用C++编写自定义转换运算符(如“static_cast”)
- Qt4:QGraphicsScene/View和自定义转换方法
- 如何将c结构体定义转换为c++
- 如何在VS2008中将#define定义转换为字符串
- 为什么模板化的用户定义转换操作符能够确定其返回类型?
- #定义转换为LPCSTR或std::string的字符串
- 错误无效的用户定义转换
- 无效的用户定义转换错误
- 是否有方法为任何指针类型定义转换操作符
- Visual C++ 不存在从"myClass1"到"myClass1"的合适用户定义转换
- 提振.Python自定义转换器