看一下代码:
#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
的默认构造函数是私有的。
然而,它可以正常工作。 我用-Wall -Wextra -Werror -pedantic
在我的g++ 4.8.3上进行了测试,并感到不可思议,但是它可以正常工作,没有任何错误或警告。
(此外,在GCC 4.9.1中似乎也可以正常工作。)
从这个页面中,我猜测如果表达式未求值,我们可以使用私有默认构造函数。 因此,我测试了以下内容以进行验证。
#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成员吗?或者对于默认构造函数有特殊规定吗?你能解释一下为什么吗?
decltype
。或者declval
。当然它不会编译。 - T.C.