SFINAE + sizeof = detect if expression compiles

前端 未结 2 470
终归单人心
终归单人心 2020-12-08 23:10

I just found out how to check if operator<< is provided for a type.

template T& lvalue_of_type();
template

        
相关标签:
2条回答
  • 2020-12-08 23:18

    It is just a combination of two well-known tricks. SFINAE says 'substitution failure is not an error' - that's exactly what you did. Using sizeof to let the compiler substitute template arguments into an expression without actually executing it is also common.

    Sorry :-)

    0 讨论(0)
  • 2020-12-08 23:19

    It's a well known technique, I'm afraid :-)

    The use of a function call in the sizeof operator instructs the compiler to perform argument deduction and function matching, at compile-time, of course. Also, with a template function, the compiler also instantiates a concrete function from a template. However, this expression does does not cause a function call to be generated. It's well described in SFINAE Sono Buoni PDF.

    Check other C++ SFINAE examples.

    0 讨论(0)
提交回复
热议问题