c++ - 仅在 C++ 中的 const 限定符上实现模板

标签 c++ templates constants

我想获得两个仅在参数的常量性上有所不同的类。

我目前做的是:
(这是一个虚拟的最小示例。)

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/

相关文章:

C++ pass-by-non-const-reference 方法 inside pass-by-const-reference 方法

c++ - 我可以阻止创建 C++ 类的非临时实例吗?

c++ - 模板特化和从其他模板类继承模板类

c++ - 类的常量成员变量可以在方法而不是构造函数中初始化吗?

objective-c - 声明二维数组大小的常量

c++ - 模板化类型宏参数中的括号,我不能使用可变参数宏

c++ - 非静态成员作为 C++ 中的默认参数

c++ - 如何在同时使用 Intel C++ 和 CUDA C++ 的 Eclipse-nsight 中创建项目?

c++ - 显式调用基类构造函数的重要性是什么?

javascript - 如何正确使用 karma-ng-html2js-preprocessor?