Question

Ok, this works on my compiler (vs2008) but I'm trying to figure out if I'm doing something non-standard. Here's a trivial example what I'm doing:

std::tr1::array<int, 3> OneTwoThree() {
    return boost::assign::list_of(1)(2)(3).to_array(std::tr1::array<int, 3>());
}

I'm cheating around the fact that the to_array adapter doesn't actually use the argument you pass into it, it's just using it to figure out the type. The examples, however, show it being used more like this:

std::tr1::array<int, 3> a = boost::assign::list_of(1)(2)(3).to_array(a);

Any ideas on whether or not just throwing a value-initialized array into to_array it is kosher? Is there a cleaner way to do this?

Was it helpful?

Solution

The to_... member functions all take an argument solely for the purpose of assisting with template argument deduction, so yes, passing a value-initialized instance of the same type you want as the return type is safe, though needlessly inefficient.

However, the to_... member functions only exist to assist broken compilers that don't properly support templated conversion operators -- why are you using them in the first place? The clean syntax would be simply:

boost::array<int, 3> OneTwoThree() {
    return boost::assign::list_of(1)(2)(3);
}

Note that I've used boost::array<> here rather than std::tr1::array<>; the reason is that the Boost.Assign library has no knowledge (yet) of TR1/C++11 standard libraries, and thus is not properly specialized for std::array<> or std::tr1::array<>. To add this specialization yourself, and consequently make the above code work with std::tr1::array<>, add the following code after including the Boost.Assign headers:

namespace boost { namespace assign_detail {

template<typename T, std::size_t sz>
type_traits::yes_type assign_is_array(std::tr1::array<T, sz> const*);

}}

(Note: only tested with Boost 1.48; earlier versions may need a different specialization.)


The syntax in your question is not default-construction, it's value-initialization.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top