使用boost ::可选恒类型 - C ++ [英] Using boost::optional with constant types - C++
问题描述
我有一个使用的boost ::可选的
来保存值的容器类。这里是code样子,
I have a container class which uses boost::optional
to hold the value. Here is the code looks like,
template<typename T>
struct traits
{
typedef T value_type;
typedef T& reference;
};
template<typename T>
struct traits<const T>
{
typedef const T value_type;
typedef const T& reference;
};
template<typename T>
struct traits<T*>
{
typedef T* value_type;
typedef T* reference;
};
template<typename T>
struct traits<const T*>
{
typedef const T* value_type;
typedef const T* reference;
};
template<typename T>
class container
{
public:
typedef typename traits<T>::reference reference;
typedef typename traits<T>::value_type value_type;
container() {}
void set(reference value) {
op.reset(value);
}
reference get() const {
return boost::get(op);
}
private:
boost::optional<value_type> op;
};
int main()
{
foo f;
container<const foo> c;
c.set(f);
return 0;
}
它可以很好地用于其它类型除了常量
。当我使用常量
类型我收到错误(常量富*
正常工作)。
It works well for other types except const
. I am getting error when I use const
types (const foo*
works fine).
- 是
的boost ::可选的
支持定类型?如果没有,我怎么能解决这个问题? - 有一个现成的性状可实现,我可以使用,而不是定义我自己的特质?
- Is
boost::optional
supports constant types? If no, how can I work around this issue? - Is there a ready made traits implementation available which I can use rather than defining my own traits?
任何帮助将是巨大的!
推荐答案
这个问题是不是与的boost ::可选的
,但与逻辑你想要什么去做。首先,创建常量的一个容器,然后您尝试修改什么遏制。我会感到惊讶,如果是工作。
The problem is not with boost::optional
, but with the logic of what you're trying to do. First you create a container of const, and then you try to modify what's contained. I would be surprised if that worked.
我想你也许应该做些什么标准集装箱(如矢量
)做的,禁止不可复制的模板参数。
I think you should probably do what standard containers (like vector
) do and forbid non-copyable template arguments.
否则,你就不得不忍受的事实,当 T
是设置
方法不起作用不可复制,并提供执行初始化的构造:
Otherwise you'll have to live with the fact that your set
method won't work when T
is non-copyable, and provide a constructor that performs the initialization:
class container
{
public:
container(reference init_value) : op(init_value) {}
};
int main()
{
foo f;
container<const foo> c(f); // OK
// c.set(f); NO
return 0;
}
这篇关于使用boost ::可选恒类型 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!