简体   繁体   中英

Decltype For Class Member Function

This code does not compile in VS2010:

template < typename A >
class X
{
    A& m_a;

public:
    X ( A& a ) : m_a ( a ) {}
    auto func ( int i ) -> decltype ( m_a ( i ) ) { return ( m_a ( i ) ); } // failing on this line
};

double f ( int a )
{
    return static_cast < double > ( a );
}

int main()
{
    X < decltype ( f ) > x ( f );
    std::cout << x.func(4) << std::endl;
    return 0;
}

The error that I get is: error C2064: term does not evaluate to a function taking 1 arguments.

It seems like the compiler doesn't think that m_a is in scope inside the decltype.

How can I fix this?

VS2010 doesn't implement decltype exactly as the standard specifies (to be fair, it's older than the final version of the standard). You should be able to get around this with hand-coded declval :

template < typename A >
class X
{
    A& m_a;
    static A& simulated_m_a();

public:
    X ( A& a ) : m_a ( a ) {}
    auto func ( int i ) -> decltype ( simulated_m_a()( i ) ) { return ( m_a ( i ) ); }
};

I've just verified on my VS2010 that it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM