C++函数调用包装器对象,将函数作为模板参数



我想只使用可用于包装C函数的C++11来构建一个模板辅助对象。

我试图将这里给出的答案从包装器函数扩展到包装器对象,这样它就可以包含状态:

#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链接(:

<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;
^

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

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

@Dani的解决方案促使我回头看看我最初提到的那个问题的另一个答案,这让我找到了自己的解决方案:

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>{}

完整的解决方案在编译器资源管理器上。

这实际上只是@Dani的解决方案和另一个问题中的C++11模板细节的融合。

最新更新