我观看了Walter Brown在Cppcon14上关于现代模板编程(第一部分,第二部分)的演讲,他在演讲中展示了他的void_tSFINAE技术.
示例:
给定一个简单的变量模板,该模板计算void所有模板参数是否格式正确:
template< class ... > using void_t = void;
Run Code Online (Sandbox Code Playgroud)
以及检查是否存在名为member的成员变量的以下特征:
template< class , class = void >
struct has_member : std::false_type
{ };
// specialized as has_member< T , void > or discarded (sfinae)
template< class T >
struct has_member< T , void_t< decltype( T::member ) > > : std::true_type
{ };
Run Code Online (Sandbox Code Playgroud)
我试图理解为什么以及如何运作.因此一个小例子:
class A {
public:
int member;
};
class B {
};
static_assert( has_member< A …Run Code Online (Sandbox Code Playgroud) 我试图创建一个示例,它将检查operator==(成员或非成员函数)的存在.检查一个类是否有成员operator==很容易,但如何检查它是否有非成员operator==?
这就是我所要做的:
#include <iostream>
struct A
{
int a;
#if 0
bool operator==( const A& rhs ) const
{
return ( a==rhs.a);
}
#endif
};
#if 1
bool operator==( const A &l,const A &r )
{
return ( l.a==r.a);
}
#endif
template < typename T >
struct opEqualExists
{
struct yes{ char a[1]; };
struct no { char a[2]; };
template <typename C> static yes test( typeof(&C::operator==) );
//template <typename C> static yes test( …Run Code Online (Sandbox Code Playgroud)