Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template function type deduction and operator<<

When I compile the following code with MSVC++, I get an error:

struct A
{
    template<typename T>
    void operator<<(T&& x)
    {
    }

};
void f()
{
}
int main()
{
    A().operator<<( f );  // ok
    A() << f;             // error

    return 0;
}

g++ and clang both compile this code fine. AFAIK, 'ok' and 'error' lines do exactly the same thing, and type T is deduced to void(&)(). Or is it void() and rvalue references to function are allowed? If so, what is their meaning? Is it ok to pass functions by reference like that? Is it MSVC++ bug that it fails to compile 'error' line? BTW, the error output:

no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
could be 'void A::operator <<<void(void)>(T (__cdecl &&))'
with[ T=void (void) ]
like image 374
dsi Avatar asked Feb 05 '13 20:02

dsi


1 Answers

Why void operator<<(T&& x)? void operator<<(T& x) serves the purpose.

Function can be called with x() inside overloaded function as below

struct A
{
    template<typename T>
    void operator<<(T& x)
    {
        x();
    }

};
void f()
{
}

int main()
{
    A().operator<<( f );
    A() << f;             
    return 0;
}
like image 102
Akshay Avatar answered Sep 28 '22 12:09

Akshay