fre*_*low 12 c++ metaprogramming sfinae
我刚刚发现了如何检查是否operator<<提供了类型.
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;
};
Run Code Online (Sandbox Code Playgroud)
这个技巧是众所周知的,还是我刚刚获得了诺贝尔奖的元编程?;)
编辑:我使代码更容易理解,更容易适应两个全局函数模板声明lvalue_of_type和rvalue_of_type.
这是一个众所周知的技术,我害怕:-)
当然,在sizeof运算符中使用函数调用指示编译器在编译时执行参数推导和函数匹配.此外,使用模板函数,编译器还可以从模板中实例化具体函数.但是,此表达式不会导致生成函数调用.它在SFINAE Sono Buoni PDF中得到了很好的描述.
查看其他C++ SFINAE示例.
| 归档时间: |
|
| 查看次数: |
2170 次 |
| 最近记录: |