You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何确保C++模板参数为非const、非引用的无修饰类型

最优实现方案

直接复用C++20标准库提供的现成类型工具和concept,不需要手写任何自定义类型萃取逻辑,样板代码最少:

#include <concepts>
#include <type_traits>

// 写法1:requires子句写法
template <typename T>
requires std::same_as<T, std::remove_cvref_t<T>>
class MyContainer {
    T* whatever;
    T moreStuff;
};

// 写法2:更简洁的模板参数内联写法,省略requires关键字
template <std::same_as<std::remove_cvref_t<T>> typename T>
class MyContainer {
    T* whatever;
    T moreStuff;
};

原理解释

  • std::remove_cvref_t<T> 是标准库提供的类型萃取工具,会一次性移除类型的顶层const、顶层volatile修饰符以及引用修饰符,得到无修饰的原始裸类型
  • std::same_as 是标准库提供的相等性判断concept,约束传入的模板参数T和移除所有修饰后的裸类型完全一致,刚好匹配非引用、无const/volatile修饰的需求

如果有多处模板需要用到这个约束,也可以单独封装成自定义concept提高复用性:

#include <concepts>
#include <type_traits>

template <typename T>
concept bare_type = std::same_as<T, std::remove_cvref_t<T>>;

// 直接使用封装好的concept
template <bare_type T>
class MyContainer {
    T* whatever;
    T moreStuff;
};

内容的提问来源于stack exchange,提问作者Askaga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 05:36:03