mercredi 27 mai 2015

Uniform initialization in return statement and explicit conversion operator to bool

I tried to force explicit conversion in return statement by means of using of uniform initialization syntax as it is in following:

#include <iostream>

#include <cstdlib>

struct A
{

    explicit
    operator bool () const
    {
        return false;
    }

    explicit
    operator bool ()
    {
        return true;
    }

};

bool
f()
{
    return {A{}}; // error: no viable conversion from 'void' to 'bool'
    // equivalent to return bool{A{}};
}

bool
g()
{
    return static_cast< bool >(A{});
}

struct B
{

    B(A) { ; }

};

B
h()
{
    return {A{}};
    // equivalent to return B{A{}};
}

inline
std::ostream &
operator << (std::ostream & _out, B const &)
{
    return _out << "B";
}

int
main()
{
    std::cout << std::boolalpha << f() << std::endl;
    std::cout << std::boolalpha << g() << std::endl;
    std::cout << h() << std::endl;
    return EXIT_SUCCESS;
}

But got an error, as it pointed against correspoinding line of code into comment.

Why deduced type of {A{}} is void? What is the meaning of return {/* something */}; in general? How it differs from obvious uniform initialization during simple initialization?

The compiler used is clang 3.6.0.

Aucun commentaire:

Enregistrer un commentaire