SFINAE + sizeof =检测表达式是否编译 [英] SFINAE + sizeof = detect if expression compiles

查看:86
本文介绍了SFINAE + sizeof =检测表达式是否编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现如何检查是否为类型提供了operator<<.

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

template<class T> T& lvalue_of_type();
template<class T> T  rvalue_of_type();

template<class T>
struct is_printable
{
    template<class U> static char test(char(*)[sizeof(
        lvalue_of_type<std::ostream>() << rvalue_of_type<U>()
    )]);
    template<class U> static long test(...);

    enum { value = 1 == sizeof test<T>(0) };
    typedef boost::integral_constant<bool, value> type;
};

这个技巧是众所周知的,还是我刚刚获得了元编程诺贝尔奖? ;)

Is this trick well-known, or have I just won the metaprogramming Nobel prize? ;)

我使用两个全局函数模板声明lvalue_of_typervalue_of_type使代码更易于理解,更易于适应.

I made the code simpler to understand and easier to adapt with two global function template declarations lvalue_of_type and rvalue_of_type.

推荐答案

这是一项众所周知的技术,恐怕:-)

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

当然,在sizeof运算符中使用函数调用会指示编译器在编译时执行参数推导和函数匹配.同样,使用模板函数,编译器还可以从模板实例化具体函数.但是,此表达式不会导致函数调用的生成.在 SFINAE Sono Buoni PDF

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.

查看其他 C ++ SFINAE示例.

这篇关于SFINAE + sizeof =检测表达式是否编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆