泛型函数包装器是否C++可能

Are generic function wrappers in C++ possible?

本文关键字:C++ 可能 是否 函数 包装 泛型      更新时间:2023-10-16

当我在使用 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
}