采用nulltpr_t的构造函数:函数定义没有声明参数

Constructor that takes nulltpr_t: function definition does not declare parameters

我有以下代码:

class C {
private:
    void *data;

public:
    constexpr C(nullptr_t) : data(nullptr) { }
    C(int i) : data(new int(i)) { }
};

我创建了一个采用 nullptr_t 的构造函数,这样我就可以拥有类似于以下的代码:

C foo(2);
// ...
foo = nullptr;

与此类似的代码以前在 MSVC 上运行过,但是此代码无法在 GCC 5.3.1 上编译(使用 -std=c++14),在 C(nullptr_t) 和 [=16= 的右括号中].即使我为参数命名(在本例中为 _),我也会得到 error: expected ')' before '_'。如果删除 constexpr 关键字,这也会失败。

为什么我无法声明这样的构造函数,有什么可能的解决方法?

你一定是"using namespace std"的粉丝,而且你just got tripped up by it:

constexpr C(std::nullptr_t) : data(nullptr) { }

gcc 5.3.1 在 --std=c++14 一致性级别编译它:

[mrsam@octopus tmp]$ cat t.C
#include <iostream>

class C {
private:
    void *data;

public:
    constexpr C(std::nullptr_t) : data(nullptr) { }
    C(int i) : data(new int(i)) { }
};
[mrsam@octopus tmp]$ g++ -g -c --std=c++14 -o t.o t.C
[mrsam@octopus tmp]$ g++ --version
g++ (GCC) 5.3.1 20160406 (Red Hat 5.3.1-6)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.