如何强制执行 C++ 命名要求“Container”

问题描述 投票:0回答:1

我正在尝试制作一个模板容器类,我希望它尽可能符合“Container”命名要求。我正在查看 this cppreference 链接,底部写着:

Other requirements
C (Container)
    DefaultConstructible
    CopyConstructible
    EqualityComparable
    Swappable
T (Type)
    CopyInsertable
    EqualityComparable
    Destructible

我想在我的代码中添加一些静态断言,这样我就不会意外地回归任何功能,并且我正在考虑将其添加到类定义中。这是我的代码的最小表示:

#include <iostream>
#include <type_traits>

template <typename T>
class MyContainer {
    public:
        MyContainer() = default;

        static_assert(std::is_default_constructible<MyContainer>::value, "MyContainer is not default constructible!");
};

int main() {
    // instantiate the object so that static assert may be evaluated
    MyContainer<int> obj1;

    std::cout << "All checks passed." << std::endl;

    return 0;
}

但是,当尝试编译此代码时(目前使用 g++ 9.4),编译在静态断言上失败。

为什么会失败?

静态断言是否意味着以这种方式使用?例如,查看我的

std::vector
类的 C++ 标准库实现,我可以清楚地看到它们使用一些像这样的静态断言(尽管不是为了检查“容器”要求是否得到满足) 此外,任何提供的答案都必须可移植到所有主要编译器(g++、clang++ 和 msvc)

c++ c++11 type-traits static-assert
1个回答
0
投票

在类体内,

MyContainer
仍然是一个不完整的类。这是因为类在两次传递中被解析:

  1. 解析所有成员声明(数据成员、
    static_assert
    等)
  2. 解析成员定义(成员函数体等)

你可以做

static_assert(std::is_default_constructible<MyContainer<int>>::value, "MyContainer is not default constructible!");

...在类之外,但这仅适用于类模板的单个专业化。

您还可以将

static_assert
放入
MyContainer
的某些成员函数中。在成员函数内,周围的类是完整的。

© www.soinside.com 2019 - 2024. All rights reserved.