如何确保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
相关产品推荐
相关产品推荐

