【发布时间】:2014-10-29 02:16:22
【问题描述】:
看代码:
#include <iostream>
#include <utility>
class test
{
private:
test() { }
public:
test foo() { return *this; }
static const char *name() { return "test"; }
};
int main()
{
std::cout << decltype(test().foo())::name() << std::endl; // 1
std::cout << decltype(std::declval<test>().foo())::name() << std::endl; // 2
}
我预计// 1 行无法编译,因为test 的默认构造函数是私有的。
However, it works well. 我难以置信地在我的 g++ 4.8.3 上使用-Wall -Wextra -Werror -pedantic 对其进行了测试,但它运行良好,没有任何错误或警告。
(此外,它似乎在 GCC 4.9.1 中也能正常工作。)
来自this page,我想如果表达式未计算,我们可以使用私有默认构造函数。因此,我测试了以下内容。
#include <iostream>
#include <utility>
class test
{
private:
test(int) { }
public:
test foo() { return *this; }
static const char *name() { return "test"; }
};
int main()
{
std::cout << decltype(test().foo())::name() << std::endl; // 1
std::cout << decltype(std::declval<test>().foo())::name() << std::endl; // 2
}
正如预期的那样,它没有被编译。
但是.... 为什么?? 这怎么可能?我们可以在未评估的表达式中使用 private 成员吗?或者默认构造函数是否有特殊规则?你能解释一下为什么吗?
【问题讨论】:
-
不能在 clang 中编译。
-
@T.C.哦真的吗?那么它可能只是GCC的错误..
-
嗯,C++98 没有
decltype。或declval。当然它不会编译。 -
@T.C.哦,我的大脑被搞砸了;;
-
嗯,它甚至在 GCC 4.9.1 中编译...
标签: c++ c++11 language-lawyer private-members decltype