【问题标题】:C++ function call wrapper object with function as template argument以函数作为模板参数的 C++ 函数调用包装器对象
【发布时间】:2020-08-04 00:09:34
【问题描述】:

我想仅使用 C++11 构建一个模板帮助器对象,该对象可用于包装 C 函数。

我正在尝试将here 给出的答案从包装函数扩展到包装对象,以便它可以包含状态:

#include <iostream>
#include <functional>

int foo(int a, int b) { return a + b; }

template<typename Fn, Fn fn, typename... Args>
class AltFuncWrapper
{
public:

    using result_type = typename std::result_of<Fn(Args...)>::type;

    bool enabled{false};

    result_type exec(Args... args)
    {
        if(enabled)
        {
            std::cout << "Run the real thing";
            return fn(std::forward<Args>(args)...);
        }
        else
        {
            std::cout << "Return default value";
            return result_type{};
        }
    }
};

int main()
{
  AltFuncWrapper<decltype(&foo), &foo> wrapper{};
  return 0;
}

但我得到以下编译器错误(CE link):

<source>: In instantiation of 'class TestDoubleWrapper<int (*)(const char*, unsigned int)throw (), chmod>':
<source>:68:51:   required from here
<source>:30:67: error: no type named 'type' in 'class std::result_of<int (*())(const char*, unsigned int)throw ()>'
     using result_type = typename std::result_of<Fn(Args...)>::type;
                                                                   ^

【问题讨论】:

    标签: c++ c++11 variadic-templates


    【解决方案1】:

    在程序中没有指定 Args 并且无法推导出它,因此它是一个空包。
    您可以使用部分特化来捕获函数的参数:

    template<auto F> class C;
    template<typename RV, typename ...Args, RV (*F)(Args...)>
    class C<F>
    {
        ...
    

    【讨论】:

    • 在我看来这个解决方案需要 C++17,而我要求使用 C++11。
    • 感谢@Dani...虽然您的解决方案不适用于 C++11,但它确实促使我回到 the other answer on that question I referred to,这让我找到了自己的解决方案。
    【解决方案2】:

    @Dani 的解决方案促使我回过头去看the other answer on that question I originally referred to,这让我找到了自己的解决方案:

    template<typename FunctionType, FunctionType func> struct AltFuncWrapper;
    template<typename ReturnType, typename... Args, ReturnType(*func)(Args...)>
    struct AltFuncWrapper<ReturnType(*)(Args...), func> {
        ...
    };
    #define MAKE_WRAPPER(func) AltFuncWrapper<decltype(&func), func>{}
    
    

    完整的解决方案是here on Compiler Explorer

    它实际上只是 @Dani 的解决方案和来自 the other question 的 C++11 模板详细信息的结合。

    【讨论】:

      猜你喜欢
      • 2016-07-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多