【问题标题】:Can one disambiguate 0 (NULL) for multiple constructors ? and assignment operators?一个可以为多个构造函数消除 0 (NULL) 的歧义吗?和赋值运算符?
【发布时间】:2011-10-12 22:40:23
【问题描述】:

在 GCC 更高版本中。当一个有多个使用引用或指针的构造函数时,一个(如果可以的话)如何消除“0”或“NULL”的歧义?

即:

class XXX
{
public:
    XXX(const XXX &tocopy);
    XXX(const char *fromAString);
    XXX(const AnotherThing *otherThing);

    operator=(const XXX &tocopy);
    operator=(const char *fromAString);
    operator=(const AnotherThing *otherThing);
};

// nice not to have to cast when setting to NULL for 
// things like smart pointers and strings. Or items that can be initialized from 
// several types of objects and setting to null means "clear"

XXX anXXX = NULL;
anXXX = 0;

// In MSC one can have an 
//    XXX(const int &nullItem) { DEBUG_ASSERT(!nullItem); setnull(); } 
// and the overloads would be disambiguated.  GCC will cause a const int to conflict
// with pointer types.

【问题讨论】:

    标签: c++ gcc compilation


    【解决方案1】:

    C++ 有一个类型系统,所以变量有类型,编译器使用这些类型来执行重载解析:

    const char * p = 0;
    const AnotherThing * q = 0;
    
    XXX a(p), b(q); // uses the respective constructors for the static type of p, q
    

    如果由于没有使用所需的指针类型之一而导致重载不明确,则会出现错误:

    XXX c(0); // error: ambiguous
    

    【讨论】:

    • 也不要使用const char*,而是更喜欢对指针的引用。并且可能使这些 ctors 明确。
    • 同意单参数构造函数最好声明为explicit
    • 对 f(const vector& x) 的 f(10) 调用会有点整洁 =) sry。
    • 意味着你不能在不强制转换 NULL 的情况下创建一个可以设置为“NULL”的变体指针类。有一个“NullType”会很好,这样人们就可以进行一个只能分配“const int 0”并且不与显式类型冲突的重载。 MSC 将通过指针和引用类型解析 const int,而 GCC 不会。
    • @peterk:不过,我看不出这有什么用。那个假定的空构造函数会做什么?你为什么不把它实现为默认构造函数呢?
    猜你喜欢
    • 1970-01-01
    • 2020-12-16
    • 2020-06-12
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    相关资源
    最近更新 更多