有没有办法对枚举使用替换失败不是错误(SFINAE)?
template <typename T>
struct Traits
{
}
template <>
struct Traits<A>
{
};
template <>
struct Traits<B>
{
enum
{
iOption = 1
};
};
template <T>
void Do()
{
// use Traits<T>::iOption
};
Then, Do<B>();
作品和Do<A>();
失败。但是,当 iOption 不存在时,我可以提供默认行为。
所以我把Do的一部分分离出来给DoOption。
template <typename T, bool bOptionExist>
void DoOption()
{
// can't use Traits<T>::iOption. do some default behavior
};
template <typename T>
void DoOption<T, true>()
{
// use Traits<T>::iOption
};
template <T>
void Do()
{
// 'Do' does not use Traits<T>::iOption. Such codes are delegated to DoOption.
DoOption<T, DoesOptionExist<T> >();
};
现在,缺失的部分是DoesOptionExist<T>
- 检查结构中是否存在 iOption 的方法。
当然 SFINAE 适用于函数名称或函数签名,但不确定
它适用于枚举值。
如果您可以使用 C++11,这完全是微不足道的:
template<class T>
struct has_nested_option{
typedef char yes;
typedef yes (&no)[2];
template<class U>
static yes test(decltype(U::option)*);
template<class U>
static no test(...);
static bool const value = sizeof(test<T>(0)) == sizeof(yes);
};
C++03 版本(令人惊讶地)相似:
template<class T>
struct has_nested_option{
typedef char yes;
typedef yes (&no)[2];
template<int>
struct test2;
template<class U>
static yes test(test2<U::option>*);
template<class U>
static no test(...);
static bool const value = sizeof(test<T>(0)) == sizeof(yes);
};
Usage:
struct foo{
enum { option = 1 };
};
struct bar{};
#include <type_traits>
template<class T>
typename std::enable_if<
has_nested_option<T>::value
>::type Do(){
}
int main(){
Do<foo>();
Do<bar>(); // error here, since you provided no other viable overload
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)