dul*_*uli 1 c++ templates if-statement
我想声明一个模板如下:
template <typename T>
{
if objects of class T have method foo(), then
const int k=1
else
if class has a static const int L then
const int k=L
else
const int k=0;
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?一般来说,我想要一种基于T(或T中定义的typedef)属性设置静态consts的机制.
外部部分当然很容易.使用boost :: mpl :: if_来决定从元函数返回哪个int_type,然后访问其中的值.没什么大不了.
你试图找出类型X是否具有函数f()的部分仍然相当简单但不幸的是你找不到通用的答案.每当你需要这种检查时,你必须编写一个自定义元函数来找出它.使用SFINAE:
template < typename T >
struct has_foo
{
typedef char (&no) [1];
typedef char (&yes) [2];
template < void (T::*)() >
struct dummy {};
template < typename S >
static yes check( dummy<&S::foo> *);
template < typename S >
static no check( ... );
enum { value = sizeof(check<T>(0)) == sizeof(yes) };
};
Run Code Online (Sandbox Code Playgroud)
编辑:哦,用BOOST_MPL_HAS_XXX()为你的静态const L创建一个检查器