gpt4 book ai didi

c++ - 折叠可变参数模板检查是否存在成员函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:48:16 24 4
gpt4 key购买 nike

我正在使用 SFINAE 习惯用法来检查类型是否具有具有特定签名的方法 (function_name())。我实现的解决方案适用于单一类型,但我想让它适用于多种类型(通过可变参数模板)。

template <typename... Other>
class has_foo {
public:
static constexpr bool value = has_foo<Other...>::value;
};

template <typename U, typename ...Other> // Error here
class has_foo {
public:
static constexpr bool value = has_foo<U>::value && has_foo<Other...>::value;
};

template <typename U>
class has_foo {
private:
template <typename T, T>
struct helper;
template <typename T>
static std::uint8_t check(helper<int (*)(size_t), &T::function_name>*);
template <typename T>
static std::uint16_t check(...);

public:
static constexpr bool value = sizeof(check<U>(0)) == sizeof(std::uint8_t);
};

template <>
class has_foo<void> {
public:
static constexpr bool value = false;
};

我收到以下错误:模板重新声明中的模板参数过多。我在这里做错了什么?

最佳答案

template <typename U, typename ...Other>
class has_foo {
public:
static constexpr bool value = has_foo<U>::value && has_foo<Other...>::value;
};

// partial template specialization
template <typename... Other>
class has_foo<void, Other...>{
public:
static constexpr bool value = has_foo<void,Other...>::value;
};

// partial template specialization
template <typename U>
class has_foo<U,void> {
private:
template <typename T, T>
struct helper;
template <typename T>
static std::uint8_t check(helper<int (*)(size_t), &T::function_name>*);
template <typename T>
static std::uint16_t check(...);

public:
static constexpr bool value = sizeof(check<U>(0)) == sizeof(std::uint8_t);
};

// partial template specialization
template <>
class has_foo<void> {
public:
static constexpr bool value = false;
};

关于c++ - 折叠可变参数模板检查是否存在成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34029561/

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