【问题标题】:Achieve template only on const qualifier in C++仅在 C++ 中的 const 限定符上实现模板
【发布时间】:2019-11-19 23:02:15
【问题描述】:

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

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

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。)

【问题讨论】:

  • 您想使用Foo_wrap&lt;&gt;/Foo_wrap&lt;const&gt; 而不是Foo/const Foo?为什么?
  • 正如所写,这是一个虚拟的最小示例。我真正需要的是编写一个自定义迭代器,它使用几个底层类,并获得这个迭代器的 const 和可变版本。
  • 这么多就明白了。然而,尚不清楚为什么您需要一个以这种特定方式工作的模板。简单地传递 Foo/const Foo 或使用模板别名,在你传入的任何内容上添加 const 将是更惯用的方法。这看起来更像是实现同一目标的一种非常复杂的方法。

标签: c++ templates constants


【解决方案1】:

您不能单独使用 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>;

如果你不需要定义其他的包装器,当然可以直接使用 Foo 在 Qualified 模板及其特化中。

您可能还对处理引用的常量性的函数std::ref / std::cref 感兴趣。

【讨论】:

  • 非常感谢,它很聪明,很整洁,而且效果很好! (确实,我需要为几个班级这样做。)
猜你喜欢
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多