C++核心准则T.150:用static_assert检查类和概念的匹配性

时间:2022-07-26
本文章向大家介绍C++核心准则T.150:用static_assert检查类和概念的匹配性,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

T.150: Check that a class matches a concept using static_assert

T.150:用static_assert检查类和概念的匹配性

Reason(原因)

If you intend for a class to match a concept, verifying that early saves users pain.

如果你希望一个类和概念相匹配,尽早地检查可以减轻用户的痛苦。

Example(示例)

class X {
public:
    X() = delete;
    X(const X&) = default;
    X(X&&) = default;
    X& operator=(const X&) = default;
    // ...
};

Somewhere, possibly in an implementation file, let the compiler check the desired properties of X:

在某处,在实现文件中也可以,让编译器检查X的期望属性:

static_assert(Default_constructible<X>);    // error: X has no default constructor
static_assert(Copyable<X>);                 // error: we forgot to define X's move constructor
Enforcement(实施建议)

Not feasible.

不可行。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t150-check-that-a-class-matches-a-concept-using-static_assert