lundi 3 août 2020

C++ function call wrapper object with function as template argument

I want to build a template helper object using only C++11 that can be used to wrap C functions.

I'm trying to extend the answer given here from a wrapper function to a wrapper object, so that it can contain state:

#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;
}

But I get the following compiler error(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;
                                                                   ^

Aucun commentaire:

Enregistrer un commentaire