Using boost :: optional with persistent types - C ++

I have a container class that uses boost::optionalto store values. Here is the code,

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 get an error when I use types const( const foo*works fine).

  • Is boost::optionalpersistent type supported ? If not, how can I get around this?
  • Is there a ready-made trait available that I can use, and not define my own traits?

Any help would be great!

+3
source share
2 answers

boost::optional, , . const, , . , .

, , , , (, vector), .

, set , T , , :

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;
}
+4
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;
};

const ? traits<const int> const int value_type const int& reference, const, ?

0

All Articles