繁体   English   中英

如何确保模板参数是非常量和非引用的

[英]How to ensure template parameter is non-const and non-reference

通常(大部分时间?)在使用模板类型参数创建类型时,您希望确保类型参数填充为非引用、非限定(非常量、非易失性)类型。 但是,像下面这样的简单定义允许用户为T填写任何类型:

template <typename T>
class MyContainer {
    T* whatever;
    T moreStuff;
};

现代 C++ 的概念应该能够解决这个问题。 什么是最好的(最好是最少样板的)方法来做到这一点?

static_assert是一个不错的选择:

#include <type_traits>

template <typename T>
class MyContainer
{
    static_assert(!std::is_reference_v<T>);
    static_assert(!std::is_const_v<T>);
    static_assert(!std::is_volatile_v<T>);

    T* whatever;
    T moreStuff;
};

我会为此使用一个概念。

template <typename T>
concept cvref_unqualified = std::is_same_v<std::remove_cvref_t<T>, T>;
template <cvref_unqualified T>
class MyContainer {...};

您可以通过static_assert检查类型

template <typename T>
class MyContainer {
    static_assert(std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, T>, "T must be non-reference, unqualified type");
    T* whatever;
    T moreStuff;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM