对于枚举来说,替换失败不是错误 (SFINAE)
有没有办法对枚举使用替换失败不是错误(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
};
然后,Do();
有效,而 Do();
失败。但是,当 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
- 一种检查结构中是否存在 iOption 的方法。 当然 SFINAE 适用于函数名称或函数签名,但不确定 它适用于枚举值。
Is there a way to use Substitution failure is not an error (SFINAE) for enum?
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>();
works and Do<A>();
fails. However, I can supply a default behavior when iOption does not exist.
So I separate out some part of Do to 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> >();
};
Now, the missing piece is DoesOptionExist<T>
- a way to check whether iOption exists in the struct.
Certainly SFINAE works for function name or function signature, but not sure
it works for enum value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您可以使用 C++11,这完全是微不足道的:
C++03 版本(令人惊讶地)相似:
用法:
If you can use C++11, this is completely trivial:
The C++03 version is (surprisingly) similar:
Usage: