【问题标题】:Is there a way to define a conversion operator for any pointer type?有没有办法为任何指针类型定义转换运算符?
【发布时间】:2014-08-30 20:14:08
【问题描述】:

我有这门课:

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 方法,它的参数似乎没有任何类型。

【问题讨论】:

  • 如果你在 C++ 的任何接口中暴露了void *,那就是设计存在问题的一个大迹象。

标签: c++ pointers operator-keyword


【解决方案1】:

是的,你可以有一个转换函数模板。

template <class T>
operator T*() {
    return static_cast<T*>(view);
}

【讨论】:

  • 这允许隐式转换为 std::string*,他只想要 POD 之类的
  • @MooingDuck 这不是我对这个问题的解释。我以为他的意思是他不想为他想要转换的每种类型编写单独的转换运算符。
【解决方案2】:

使用模板允许转换为所有类型,然后使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2017-08-26
    • 1970-01-01
    • 2020-06-06
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多