gpt4 book ai didi

c++ - 如何实现is_polymorphic_functor?

转载 作者:太空狗 更新时间:2023-10-29 23:45:55 26 4
gpt4 key购买 nike

我正在尝试实现 is_polymorphic_functor 元函数以获得以下结果:

//non-polymorphic functor
template<typename T> struct X { void operator()(T); };

//polymorphic functor
struct Y { template<typename T> void operator()(T); };

std::cout << is_polymorphic_functor<X<int>>::value << std::endl; //false
std::cout << is_polymorphic_functor<Y>::value << std::endl; //true

这只是一个例子。理想情况下,它应该适用于任何 数量的参数,即operator()(T...)Here are few more test cases我用它来测试@Andrei Tita 的解决方案,该解决方案在两个测试用例中都失败了。

我试过这个:

template<typename F>
struct is_polymorphic_functor
{
private:
typedef struct { char x[1]; } yes;
typedef struct { char x[10]; } no;

static yes check(...);

template<typename T >
static no check(T*, char (*) [sizeof(functor_traits<T>)] = 0 );
public:
static const bool value = sizeof(check(static_cast<F*>(0))) == sizeof(yes);
};

它试图利用以下 functor_traits 的实现:

//functor traits
template <typename T>
struct functor_traits : functor_traits<decltype(&T::operator())>{};

template <typename C, typename R, typename... A>
struct functor_traits<R(C::*)(A...) const> : functor_traits<R(C::*)(A...)>{};

template <typename C, typename R, typename... A>
struct functor_traits<R(C::*)(A...)>
{
static const size_t arity = sizeof...(A) };

typedef R result_type;

template <size_t i>
struct arg
{
typedef typename std::tuple_element<i, std::tuple<A...>>::type type;
};
};

对于多态仿函数给出了以下错误:

error: decltype cannot resolve address of overloaded function

如何解决这个问题并使 is_polymorphic_functor 按预期工作?

最佳答案

这对我有用:

template<typename T>
struct is_polymorphic_functor
{
private:
//test if type U has operator()(V)
template<typename U, typename V>
static auto ftest(U *u, V* v) -> decltype((*u)(*v), char(0));
static std::array<char, 2> ftest(...);

struct private_type { };

public:
static const bool value = sizeof(ftest((T*)nullptr, (private_type*)nullptr)) == 1;
};

关于c++ - 如何实现is_polymorphic_functor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14912703/

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