gpt4 book ai didi

c++ - C++ 中的通用函数包装器是否可行?

转载 作者:太空狗 更新时间:2023-10-29 23:19:06 24 4
gpt4 key购买 nike

这是在我调查使用 decltype 时 boost::fusion::fused 函数包装器中的一个错误时出现的。问题似乎是无效的 decltype 是编译错误,即使不会使用需要它的模板实例化,我也不知道如何绕过它来创建通用函数包装器。

这是我对单参数包装器的尝试:

#include <utility>
#include <type_traits>

template <class T>
typename std::add_rvalue_reference<T>::type declval();

template <class Fn, class Arg>
struct get_return_type
{
typedef decltype(declval<Fn>()(declval<Arg>())) type;
};

template <class Fn>
struct wrapper
{
explicit wrapper(Fn fn) : fn(fn) {}
Fn fn;

template <class Arg>
typename get_return_type<Fn,Arg&&>::type
operator()(Arg&& arg)
{
return fn(std::forward<Arg>(arg));
}

template <class Arg>
typename get_return_type<const Fn,Arg&&>::type
operator()(Arg&& arg)
{
return fn(std::forward<Arg>(arg));
}
};

问题是,这不适用于非 const 版本的参数不能转换为 const 版本的参数的情况。例如:

#include <iostream>

struct x {};
struct y {};

struct foo
{
void operator()(x) { std::cout << "void operator()(x)" << std::endl; }
void operator()(y) const { std::cout << "void operator()(y) const" << std::endl; }
};

int main()
{
wrapper<foo> b = wrapper<foo>(foo());
b(x()); // fail
}

在我看来,由 void operator()(y) const 引起的 decltype 表达式失败应该只是导致该函数因 SFINAE 而被删除。

最佳答案

这是在 g++ 4.6.1 上编译良好的代码:

#include <utility>
#include <type_traits>
#include <iostream>

template <class Fn, class Arg>
struct get_return_type
{
typedef decltype( std::declval<Fn>() ( std::declval<Arg>() ) ) type;
};

template <class Fn>
struct wrapper
{
explicit wrapper(Fn fn) : fn(fn) {}
Fn fn;

template <class Arg>
typename get_return_type<Fn,Arg&&>::type
operator()(Arg&& arg)
{
return fn(std::forward<Arg>(arg));
}

template <class Arg>
typename get_return_type< const Fn,Arg&&>::type
operator()(Arg&& arg) const
{
return fn(std::forward<Arg>(arg));
}
};

struct x {};
struct y {};

struct foo
{
x* operator()(x) { std::cout << "x* operator()(x)" << std::endl; return nullptr; }
x operator()(x) const { std::cout << "x operator()(x) const" << std::endl; return x(); }
y* operator()(y) { std::cout << "y* operator()(y)" << std::endl; return nullptr; }
y operator()(y) const { std::cout << "y operator()(y) const" << std::endl; return y(); }
};

template <class Fn>
void test_foo(Fn fn)
{
// make sure all operator() overloads are callable
const Fn& cfn = fn;

x* a = fn(x());
x b = cfn(x());
y* c = fn(y());
y d = cfn(y());
(void)a;(void)b;(void)c;(void)d;
}

int main()
{
test_foo(foo());
test_foo(wrapper<foo>(foo())); // fail
}

关于c++ - C++ 中的通用函数包装器是否可行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10646469/

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