not able to assign `boost::assign::list_of` to `static const std::vector`

70 Views Asked by At

I am using C++ 03, previously I have code:

static const std::vector<std::pair<uint16_t, uint16_t>> a = boost::assign::list_of(std::make_pair(1,1)) std::make_pair(2,2));

and it worked.

Now I need to add an If block and in different cases a needs to be different values, so I have:

static const std::vector<std::pair<uint16_t, uint16_t>> a;
if (xxx){
    a = boost::assign::list_of(std::make_pair(1,1)) std::make_pair(2,2));
}
else{
    a = boost::assign::list_of(std::make_pair(1,1)) std::make_pair(3,3));
}

and I got error:ambiguious overload for operator= .......... how can I fix it?

1

There are 1 best solutions below

0
Alan Birtles On

If you look closer at your error message you'll probably find mention of not being able to convert to const. As a is const you can't assign to it. You need to either make a non-const or you need to initialise it on assignment. You can do this either with a ternary:

static const std::vector<std::pair<uint16_t, uint16_t> > a = xxx ?
    boost::assign::list_of(std::make_pair(1,1))(std::make_pair(2,2)) :
    boost::assign::list_of(std::make_pair(1,1))(std::make_pair(3,3));

Or by using a function:

std::vector<std::pair<uint16_t, uint16_t> > make_a()
{
    if (xxx)
    {
        return boost::assign::list_of(std::make_pair(1,1))(std::make_pair(2,2));
    }
    else
    {
        return boost::assign::list_of(std::make_pair(1,1))(std::make_pair(3,3));
    }
}
static const std::vector<std::pair<uint16_t, uint16_t> > a = make_a();