Boost logo

Boost :

Subject: [boost] Would a construct_cast<T>(u..) be useful?
From: Johannes Schaub (litb) (schaub.johannes_at_[hidden])
Date: 2011-04-17 10:40:11

I was wondering whether it makes sense to have another kind of cast in
boost, which behaves like the following:

    template<typename T, typename ...U>
    T construct_cast(U &&... u) {
      T t(std::forward<U>(u)...);
      return t;

This cast works if std::is_constructible<T, U...>::value is true, and fails
if it is false.

It presents a slightly more explicit form of boost::implicit_cast<T> in that
explicit constructors of T are allowed, and for the case of a single-
elemented parameter pack, explicit conversion functions of U converting to
"T" are allowed. It does not allow non-implicit conversions like void* ->
nonvoid*, Base* -> Derived*.

Advantages over not having construct_cast:

- Converting expressions to "bool" by use of "contextually converted to
bool", without using things like "!!x" or "x ? true : false" (the first may
trigger user defined opeators for "operator!", which may not be desired).
- No need for introducing a temporary named variable like the above "t".
- If all you want is to consider contexual conversions, explicit
constructors and conversion functions, this can be used. All these
conversion seem "safe", compared to the set of conversions allowed by T(u)
and even static_cast<T>(u).

What do you think about it?

Boost list run by bdawes at, gregod at, cpdaniel at, john at