[软件设计/软件工程] g++ - 如何禁用从 0 到指针类型的隐式转换?

[复制链接]
发表于 2022-5-4 15:20:56
问题
具体来说,我希望以下代码失败:
  1. void a(void*){}
  2. int main(){
  3.     a(0); // FAIL
  4.     a(NULL); // FAIL
  5.     a(nullptr); // success
  6. }
复制代码

我希望编译以下代码:
  1. void a(int){}
  2. void a(void*){}
  3. int main(){
  4.     a(0); // calls first a
  5.     a(NULL); // calls first a; that's why I have -Werror
  6.     a(nullptr); // calls second a
  7. }
复制代码

以下代码目前无法编译,但应该按照我的规则工作:
  1. void a(std::size_t){}
  2. void a(void*){}
  3. int main(){
  4.     a(0); // two candidates
  5. }
复制代码

你知道如何让 g++ 做到这一点吗?

回答
这可能并不完美,但如果你真的想使用 int 和指针重载,你可以使用这样的辅助类:
  1. #include <iostream>
  2. #include <iomanip>
  3. using std::cout;
  4. using std::endl;

  5. template<typename T = void> class ptr {
  6.     T* it;
  7. public:
  8.     ptr(T* it = nullptr): it(it) {}
  9.     ptr(const ptr<T>&) = default;
  10.     ptr& operator = (const ptr<T>&) = default;
  11.     operator T* () { return it; }
  12.     T& operator * () { return *it; }
  13.     T* operator -> () { return it; }
  14.     ptr& operator += (int x) { it += x; return *this; }
  15.     ptr& operator -= (int x) { it -= x; return *this; }
  16.     ptr& operator ++ () { ++it; return *this; }
  17. //  etc...
  18. public:
  19.     template<typename P>
  20.       ptr(P* it): it(it) {}
  21.     template<typename P>
  22.       ptr(ptr<P> it): it((T*)it) {}
  23. };
  24. template<> class ptr<void> {
  25.     void* it;
  26. public:
  27.     ptr(void* it = nullptr): it(it) {}
  28.     ptr(const ptr<void>&) = default;
  29.     ptr& operator = (const ptr<void>&) = default;
  30.     operator void* () { return it; }
  31. public:
  32.     template<typename P>
  33.       ptr(P* it): it(it) {}
  34.     template<typename P>
  35.       ptr(ptr<P> it): it((void*)it) {}
  36. };

  37. void a(std::size_t x) {
  38.     cout << "first: " << x << endl; }
  39. void a(ptr<const int> p) {
  40.     cout << "second: " << (p ? *p : -1) << endl; }
  41. void a(ptr<int> p, ptr<> q) {
  42.     cout << "third: " << (p ? *p : -1) << ", "
  43.         << (q ? "some" : "null") << endl;
  44.     a(p); }
  45. int main(){
  46.     a(0);           // first: 0
  47.     a(NULL);        // first: 0 but warning [-Wconversion-null]
  48.     a(new int(3), nullptr); // third: 3, null + second: 3
  49. }
复制代码

它还没有完成(可能删除显式,添加更多运算符,从 nullptr_t 进行特殊转换等),只是一个想法。

编辑:对代码、模板构造函数和转换为 ptr<const int> 的更改很少测试。





上一篇:电子表格“=QUERY” join() 的等效函数?
下一篇:如何获取数组元素的序列?

使用道具 举报

Archiver|手机版|小黑屋|吾爱开源 |网站地图

Copyright 2011 - 2012 Lnqq.NET.All Rights Reserved( ICP备案粤ICP备14042591号-1粤ICP14042591号 )

关于本站 - 版权申明 - 侵删联系 - Ln Studio! - 广告联系

本站资源来自互联网,仅供用户测试使用,相关版权归原作者所有

快速回复 返回顶部 返回列表