gpt4 book ai didi

c++ - sfinae 使用 decltype 检查静态成员

转载 作者:可可西里 更新时间:2023-11-01 15:51:22 25 4
gpt4 key购买 nike

我写了下面的代码来尝试检测一个类型是否有一个静态成员变量。不幸的是,它总是返回变量不存在。

有人能告诉我哪里错了吗?我正在使用 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 所指出的,它正在检测静态成员和非静态成员。

关于c++ - sfinae 使用 decltype 检查静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11927032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com