gpt4 book ai didi

c++ - CPP 元编程 : contains function for tuples

转载 作者:行者123 更新时间:2023-11-28 01:39:00 25 4
gpt4 key购买 nike

我想实现一个 contains 函数,它检查元组中是否包含特定类型。

特别是我想尝试 std::condition 模板来完成这项工作。但是编译时出现以下错误:

In file included from /Users/harald/Desktop/Meta/main.cpp:2:
/Users/harald/Desktop/Meta/type_set.h:19:70: error: no member named 'value' in 'type_set_contains<float, type_set<int, float, double> >'
constexpr bool type_set_contains_v = type_set_contains<Type, Tuple>::value;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
/Users/harald/Desktop/Meta/main.cpp:6:18: note: in instantiation of variable template specialization 'type_set_contains_v<float, type_set<int, float, double> >' requested here
std::cout << type_set_contains_v<float, type_set<int, float, double>>;

到目前为止我的代码是:

#include <type_traits>

template <typename... Types>
class type_set {};

template<typename Type, typename Tuple>
struct type_set_contains: public std::false_type{};

template<typename Type, typename Head, typename... Rest>
struct type_set_contains<Type, type_set<Head, Rest...>> :
public std::conditional<std::is_same<Type, Head>::value, std::true_type,
type_set_contains<Type, type_set<Rest...>>>{};

template<typename Type, typename Tuple>
constexpr bool type_set_contains_v = type_set_contains<Type, Tuple>::value;

我尝试通过调用这一行来执行函数:

type_set_contains_v<float, type_set<int, float, double>>;

那么我的错误是什么?

最佳答案

您继承自 std::conditional 而不是 std::conditional_t。错误消息 error: no member named 'value' 是正确的,因为 std::conditional 没有 value 成员。

此外,您提到了元组,但您使用的是自定义 type_set 类型。如果你想普遍接受 std::tupletype_set 或其他可变模板类型,你需要使用 template template parameter .

template<typename T, typename TypeSet>
struct type_set_contains : public std::false_type {};

template<typename T, template<typename...> class TypeSet, typename Head, typename ...Ts>
struct type_set_contains<T, TypeSet<Head, Ts...>> :
std::conditional_t<std::is_same<Head, T>::value, std::true_type, type_set_contains<T, TypeSet<Ts...>>> {};

template<typename T, typename TypeSet>
constexpr bool const type_set_contains_v = type_set_contains<T, TypeSet>::value;

Live demo

关于c++ - CPP 元编程 : contains function for tuples,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48131315/

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