c++ - 来自引用包装器的 Const 引用包装器

标签 c++ c++11 reference constants template-classes

考虑以下引用包装器:

template <class T>
struct wrapper
{
    wrapper(T& x): reference{x} {}
    void set(const T& x) {reference = x;}
    T& get() const {return reference;}
    T& reference;
};

我在想:

  • 如何仅通过模板别名声明 const 引用包装器 template <class T> using const_wrapper = /* const wrapper<T> or wrapper<const T>?*/
  • 如果在此状态下不可能,如何更改包装器结构以使前面的点成为可能?
  • 如何解决以下问题:int i = 42; wrapper<const char> w(i);将编译但不工作(我想阻止构造函数)
  • 具体是什么问题,iteratorconst_iterator一般有两种不同的实现方式?

最佳答案

How to declare a const reference wrapper through a template alias only template <class T> using const_wrapper = /* const wrapper<T> or wrapper<const T>?*/

显然那将是:

template <class T> using const_wrapper = wrapper<const T>;

包含的类型是const ,而不是包装器。

但是请注意,您的 set如果 T 则无法调用函数是const .这是出于显而易见的原因;你不能改变 const值(value)。

How to solve the following problem: int i = 42; wrapper<const char> w(i); will compile but not work (I would like to block the constructor)

这个其实有点复杂。如果用户尝试使用与 T 不完全匹配的类型,您必须做的是导致编译失败。 .为此,您需要使用 =delete C++11 的特点:

template <class T>
struct wrapper
{
    wrapper(T& x): reference{x} {}
    template<typename U>
        wrapper(const U &) = delete;
    //...
};

当任何人传递的类型与 T 不完全匹配时,将使用第二个构造函数.因为它是 delete d,当人们试图使用它时,你会得到一个编译器错误。

For what exact problem, iterator and const_iterator general have two different implementations?

谁说他们这样做了?它们甚至不需要是不同类型(例如考虑 set 的迭代器),更不用说需要不同的实现了。它们只是不同的类型别名。

关于c++ - 来自引用包装器的 Const 引用包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34092093/

相关文章:

c++ - 如何检查两个矩阵是否相同?

c++ - 在类模板中存储可变参数

c++ - 语法 "ContextRegistrar_##ContextType"的含义

c++ - 漏洞?使用 findContours() 时增加每次迭代的内存使用量

c++ - 什么时候一个模板比另一个模板更专业? 'And'/'Or' 与逻辑混淆。

php - PHP 中的数组是作为值复制还是作为对新变量的引用,以及何时传递给函数?

php - 如何传递对 call_user_func 的引用?

perl - 将标量和散列传递给 Perl 中的子程序

c++ - 为什么汇编时会出现 "Access violation reading location"错误?

c++ - 在 C++ 中选择运行时数组或 vector