我想获得两个仅在参数的常量性上有所不同的类。
我目前做的是:
(这是一个虚拟的最小示例。)
template <typename T>
struct Wrapper {
Wrapper(T & t):
t(t) {
}
T & t;
};
class Foo;
using Foo_wrapper = Wrapper<Foo>;
using Const_Foo_wrapper = Wrapper<const Foo>;
我希望我的模板仅在 Foo 上声明,并且仅在 const 限定符上有所不同。
那会是这样的:
(这是无效语法,尝试给出想法。)
class Foo;
template <qualifier Q>
struct Foo_base_wrapper {
Wrapper(Q Foo & t):
t(t) {
}
Q Foo & t;
};
using Foo_wrapper = Foo_base_wrapper<none>;
using Const_Foo_wrapper = Foo_base_wrapper<const>;
有什么办法可以实现吗?
(一个接近的解决方案可能与概念有关,但那将更加通用和复杂,而且我没有 C++ 20。)
最佳答案
您不能单独使用 const
关键字,但您可以使用模板(部分)特化来控制类似这样的类型的常量性。
enum Qualifier { Mutable, Const };
template<typename T, Qualifier Q>
struct Qualified
{
using type = T;
};
template<typename T>
struct Qualified<T, Const>
{
using type = const T;
};
template <Qualifier Q = Mutable>
struct Foo_base_wrapper
{
using QualifiedFoo = typename Qualified<Foo, Q>::type;
Foo_base_wrapper(QualifiedFoo & t) : t(t)
{ }
QualifiedFoo & t;
};
using Foo_wrapper = Foo_base_wrapper<>; // or explicitly Foo_base_wrapper<Mutable>
using Const_Foo_wrapper = Foo_base_wrapper<Const>;
如果您不必定义其他包装器,您当然可以在 Qualified 模板及其特化中直接使用 Foo。
您可能还对函数感兴趣 std::ref / std::cref
处理引用的常量。
关于c++ - 仅在 C++ 中的 const 限定符上实现模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58944183/