SFINAE decltype逗号运算符技巧
SFINAE decltype comma operator trick
在阅读了Matthieu在这里的回答后,我决定自己尝试一下。
我的尝试编译失败,因为SFINAE没有启动并剔除尝试访问T::foo
的has_foo
函数。
error: ‘struct Bar’ has no member named ‘foo’
我是错过了什么,还是我试图以这种方式做的事情不可能?
(我使用的是gcc-4.7.2)
完整示例如下:
#include <iostream>
// culled by SFINAE if foo does not exist
template<typename T>
constexpr auto has_foo(T& t) -> decltype((void)t.foo, bool())
{
return true;
}
// catch-all fallback for items with no foo
constexpr bool has_foo(...)
{
return false;
}
//-----------------------------------------------------
template<typename T, bool>
struct GetFoo
{
static int value(T& t)
{
return t.foo;
}
};
template<typename T>
struct GetFoo<T, false>
{
static int value(T&)
{
return 0;
}
};
//-----------------------------------------------------
template<typename T>
int get_foo(T& t)
{
return GetFoo<T, has_foo(t)>::value(t);
}
//-----------------------------------------------------
struct Bar
{
int val;
};
int main()
{
Bar b { 5 };
std::cout << get_foo(b) << std::endl;
return 0;
}
AFAICS的主要问题是使用运行时引用作为constexpr
函数参数。更换这个效果很好。
#include <iostream>
// culled by SFINAE if foo does not exist
template<typename T>
constexpr auto has_foo(int) -> decltype(std::declval<T>().foo, bool())
{
return true;
}
// catch-all fallback for items with no foo
template<typename T> constexpr bool has_foo(...)
{
return false;
}
//-----------------------------------------------------
template<typename T, bool>
struct GetFoo
{
static int value(T& t)
{
return t.foo;
}
};
template<typename T>
struct GetFoo<T, false>
{
static int value(T&)
{
return 0;
}
};
//-----------------------------------------------------
template<typename T>
int get_foo(T& t)
{
return GetFoo<T, has_foo<T>(0)>::value(t);
}
//-----------------------------------------------------
struct Bar
{
int val;
};
struct Foo {
int foo;
};
int main()
{
Bar b { 5 };
Foo f { 5 };
std::cout << get_foo(b) << std::endl;
std::cout << get_foo(f) << std::endl;
return 0;
}
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- C++decltype和圆括号-为什么
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 有条件地选择带有 decltype() 和三元运算符的类型
- 不完整类型的调用运算符的 decltype 的特殊行为
- SFINAE:运算符上的 decltype []
- 为什么我不能对提取运算符进行 decltype
- 如何将 decltype 应用于运算符 [] 声明中的成员函数
- SFINAE decltype逗号运算符技巧
- decltype和C++中的scope运算符
- decltype,重载运算符的递归类型推导