SFINAE 使用 decltype 检查静态成员
sfinae check for static member using decltype
我编写了以下代码来尝试检测类型是否具有静态成员变量。 不幸的是,它总是返回变量不存在。
有人可以告诉我哪里出错了吗? 我正在使用 g++ 4.7.1。
#include <iostream>
#include <utility>
#include <type_traits>
using namespace std;
template <class T>
class has_is_baz
{
template<class U,
typename std::enable_if<std::is_same<bool, decltype(U::is_baz)>::value>::type...>
static std::true_type check(int);
template <class>
static std::false_type check(...);
public:
static constexpr bool value = decltype(check<T>(0))::value;
};
struct foo { };
struct bar
{
static constexpr bool is_baz = true;
};
int main()
{
cout << has_is_baz<foo>::value << 'n';
cout << has_is_baz<bar>::value << 'n';
}
主要问题是:
std::is_same<bool, decltype(bar::is_baz)>::value == false
然后你的SFINAE总是失败。我已经重写了has_is_baz
特征,它现在可以工作了:
#include <iostream>
#include <utility>
#include <type_traits>
using namespace std;
template <class T>
class has_is_baz
{
template<class U, class = typename std::enable_if<!std::is_member_pointer<decltype(&U::is_baz)>::value>::type>
static std::true_type check(int);
template <class>
static std::false_type check(...);
public:
static constexpr bool value = decltype(check<T>(0))::value;
};
struct foo { };
struct bar
{
static constexpr bool is_baz = true;
};
struct not_static {
bool is_baz;
};
int main()
{
cout << has_is_baz<foo>::value << 'n';
cout << has_is_baz<bar>::value << 'n';
cout << has_is_baz<not_static>::value << 'n';
}
编辑:我已经修复了类型特征。如@litb所示,它正在检测静态成员和非静态成员。
代码中的问题是constexpr
对象是隐式const
的,这意味着您对相同类型的测试应该是:
std::is_same<const bool, decltype(U::is_baz)>::value
这在 §7.1.5 [dcl.constexpr]/9 的标准中有所规定
。对象声明中使用的 constexpr 说明符将对象声明为 const。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- (C++)为什么静态成员可以在初始化之前使用
- 类的全局对象和静态成员
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 模板化类中静态成员的延迟初始化
- 使用静态成员声明类时遇到问题
- C++:是否可以使用非静态成员变量模板?
- 静态代码检查器抱怨.虚惊一场?
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 如何在复杂继承中访问静态成员变量
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- C++构造函数和静态成员
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 静态成员变量不会由 gettext 转换
- 如何检查静态成员变量模板?
- SFINAE 使用 decltype 检查静态成员
- 检查类是否具有给定签名的静态成员函数