g ++-如何禁用从0到指针类型的隐式转换? [英] g++ - how do I disable implicit conversion from 0 to pointer types?

查看:65
本文介绍了g ++-如何禁用从0到指针类型的隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体地说,我希望以下代码失败:

Specifically, I want the following code to fail:

void a(void*){}
int main(){
    a(0); // FAIL
    a(NULL); // FAIL
    a(nullptr); // success
}

我想编译以下代码:

void a(int){}
void a(void*){}
int main(){
    a(0); // calls first a
    a(NULL); // calls first a; that's why I have -Werror
    a(nullptr); // calls second a
}

以下代码当前无法编译,但应根据我的规则:

The following code does not compile currently, but should according to my rule:

void a(std::size_t){}
void a(void*){}
int main(){
    a(0); // two candidates
}

有什么主意如何使g ++像这样吗?

Any idea how to make g++ behave like that?

推荐答案

这可能并不完美,但是如果您确实想要int和指针重载,则可以使用类似以下的帮助器类:

This may not be perfect, but if you trully want to have overloads with int and pointer, you could use some helper class like this:

#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;

template<typename T = void> class ptr {
    T* it;
public:
    ptr(T* it = nullptr): it(it) {}
    ptr(const ptr<T>&) = default;
    ptr& operator = (const ptr<T>&) = default;
    operator T* () { return it; }
    T& operator * () { return *it; }
    T* operator -> () { return it; }
    ptr& operator += (int x) { it += x; return *this; }
    ptr& operator -= (int x) { it -= x; return *this; }
    ptr& operator ++ () { ++it; return *this; }
//  etc...
public:
    template<typename P>
      ptr(P* it): it(it) {}
    template<typename P>
      ptr(ptr<P> it): it((T*)it) {}
};
template<> class ptr<void> {
    void* it;
public:
    ptr(void* it = nullptr): it(it) {}
    ptr(const ptr<void>&) = default;
    ptr& operator = (const ptr<void>&) = default;
    operator void* () { return it; }
public:
    template<typename P>
      ptr(P* it): it(it) {}
    template<typename P>
      ptr(ptr<P> it): it((void*)it) {}
};

void a(std::size_t x) {
    cout << "first: " << x << endl; }
void a(ptr<const int> p) {
    cout << "second: " << (p ? *p : -1) << endl; }
void a(ptr<int> p, ptr<> q) {
    cout << "third: " << (p ? *p : -1) << ", "
        << (q ? "some" : "null") << endl;
    a(p); }
int main(){
    a(0);           // first: 0
    a(NULL);        // first: 0 but warning [-Wconversion-null]
    a(new int(3), nullptr); // third: 3, null + second: 3
}

这还没有完成(也许删除该显式,添加更多的运算符,从nullptr_t进行特殊转换等),公正和想法.

It is not finished (maybe remove that explicit, add more operators, special conversion from nullptr_t, etc), just and idea.

:代码,模板构造函数中的少量更改以及向 ptr< const int> 测试的转换.

Few changes in code, template constructors and conversion to ptr<const int> test.

这篇关于g ++-如何禁用从0到指针类型的隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆