考虑以下引用包装器:
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);
将编译但不工作(我想阻止构造函数) - 具体是什么问题,
iterator
和const_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/