c++ - 有没有办法避免隐式转换为 void*?

标签 c++ implicit-conversion void-pointers

我使用的 API 接受 void*在某些功能上。我经常不小心将错误的指针类型传递给函数,当然它编译得很好,但在运行时不起作用。
有没有办法禁用隐式转换为 void*指向某个类的指针?

最佳答案

您可以为 API 函数添加已删除的重载:

// API function
void api(void* p) {
    // ... 
}

// Special case for nullptr
inline void api(std::nullptr_t) {
    api((void*)nullptr);
}

// Everything else is disabled
template <class ...T>
void api(T&&... t) = delete;

int main() {
    int i = 0;
    void* p = &i;
    api(p); // Compiles
    // api(&i); // Doesn't compile
}

关于c++ - 有没有办法避免隐式转换为 void*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68673443/

相关文章:

c++ - gmock : Why isn't EXPECT_CALL detecting the function call in my test?

c++ - 使用 std::forward 的构造函数

c - 带有空指针的图表的奇怪输出

c++ - 从转换为基对象的 Void 指针调用派生类方法

时间:2019-03-08 标签:c++typeidoperator

C++ 矩阵类重载运算符通过引用返回

scala - 隐式转换不适用于类型安全的构建器模式

来自父特征的 Scala 隐式转换

c# - 是否有任何带有 C# .Net 的隐式转换器 'out of the box'?

c - 取消引用 void 指针