gpt4 book ai didi

c++ - 从私有(private)嵌套类型继承在 C++11 中是否合法?

转载 作者:太空狗 更新时间:2023-10-29 20:28:23 25 4
gpt4 key购买 nike

我想做的是在我的库类中有一个可变大小的 POD 作为 Pimpl:

// header file
class foo {
public:
// ctors, copy, move, dtor, etc.

private:
struct impl; // forward-declared
impl* pimpl; // pointer to private implementation
};

然后像这样定义几个固定大小的实现:

// .cpp implementation file
struct foo::impl {
uint32_t refs;
uint32_t size;
uint32_t len;
uint32_t data;
};

static_assert( sizeof( typename foo::impl ) == 16, "paranoia" );

namespace { // anonymous
typedef typename foo::impl base;

template <size_t S>
struct block : base {
static_assert( S > 16, "invalid block size" );
static_assert((( S - 1 ) & S ) == 0, "block size must be power of 2" );

uint8_t pad[S - 16];
};

typedef block<64> block64;
typedef block<128> block128;
// ...
}

// foo implementation using the above PODs

GCC 版本 4.6 和 4.7 使用 -std=c++0x -Wall -pedantic 编译没有问题,但我仍然不清楚使用私有(private)嵌套类型名称的合法性。仔细阅读我的 [可能是过时的草稿] C++11 标准拷贝并没有给我任何更好的线索。

如果有人能指出任何可以证明这一点(合法与否)的东西(最好是标准中的一个部分),我将永远感激不已。

最佳答案

您的实现不合法:对 foo::impl 的访问是私有(private)的,即只有 foo 的定义或其成员可以引用它。在实现文件中,您在命名空间范围内引用该名称。

标准的相关部分是 11 [class.access] 第 1 段和第 4 段。

关于c++ - 从私有(private)嵌套类型继承在 C++11 中是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13383351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com