std :: is_default_constructible与私有访问和朋友功能 [英] std::is_default_constructible with private access and friend function

查看:53
本文介绍了std :: is_default_constructible与私有访问和朋友功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶地发现 std :: is_default_constructible 似乎忽略了朋友的访问.当在类中声明一个默认的构造函数私有,然后将一个函数作为朋友时,我希望 std :: is_default_constructible 返回true.

I was surprised to discover that std::is_default_constructible appears to ignore friend access. When declaring a default constructor private in a class and then friending a function, I'd expect that std::is_default_constructible would return true.

示例:我在Wandbox上运行了以下命令: https://wandbox.org/使用Clang 5.0.0和C ++ 17下的GCC 7.2.0.

Example: I ran the following on Wandbox: https://wandbox.org/ using Clang 5.0.0 and GCC 7.2.0 under C++17.

#include <type_traits>
#include <cassert>

class PrivateConstructor
{
    private:
        PrivateConstructor() = default;
        friend void doIt();

};

void doIt()
{
        bool isConstructible = std::is_default_constructible<PrivateConstructor>::value;
        PrivateConstructor value;
        assert(isConstructible); // FAILS!
}
int main(int,char**)
{
    doIt();
    return 0;
}

此代码可以编译,但是断言失败.是在标准中明确定义的,还是可能的编译器错误?

This code compiles but the assertion fails. Is the defined explicitly in the standard or is this a possible compiler bug?

推荐答案

您已将函数 doIt()声明为该类的朋友,但该函数无法访问私有类成员.取而代之的是,函数 std :: is_deafault_constructible 访问类成员.

You declared the function doIt() to be friend of the class, but that function does not access the private class members. Instead, the function std::is_deafault_constructible accesses the class members.

template< class T >
struct is_default_constructible : std::is_constructible<T> {};

正确的方法是将 std :: is_default_constructible 声明为朋友类:

The proper way is declaring std::is_default_constructible to be a friend class:

friend class is_default_constructible<PrivateConstructor>;

这篇关于std :: is_default_constructible与私有访问和朋友功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆