是否有方法为任何指针类型定义转换操作符

Is there a way to define a conversion operator for any pointer type?

本文关键字:定义 转换 操作符 类型 指针 有方法 任何 是否      更新时间:2023-10-16

我有这样一个类:

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