C++03. Test for rvalue-vs-lvalue at compile-time, not just at runtime

前端 未结 2 2035
耶瑟儿~
耶瑟儿~ 2020-12-08 20:46

In C++03, Boost\'s Foreach, using this interesting technique, can detect at run-time whether an expression is an lvalue or an rvalue. (I found that via this StackOv

2条回答
  •  清歌不尽
    2020-12-08 21:05

    The address-of operator (&) can only be used with an lvalue. So if you used it in an SFINAE test, you could distinguish at compile-time.

    A static assertion could look like:

    #define STATIC_ASSERT_IS_LVALUE(x) ( (sizeof &(x)), (x) )
    

    A trait version might be:

    template
    struct has_lvalue_subscript
    {
        typedef char yes[1];
        typedef char no[2];
    
        yes fn( char (*)[sizeof (&(((T*)0)->operator[](0))] );
        no fn(...);
        enum { value = sizeof(fn(0)) == 1 };
    };
    

    and could be used like

    has_lvalue_subscript< std::vector >::value
    

    (Warning: not tested)

    I can't think of any way to test an arbitrary expression valid in the caller's context, without breaking compilation on failure.

提交回复
热议问题