具有函数作为模板参数的 C++ 函数调用包装器对象
C++ function call wrapper object with function as template argument
我想仅使用 C++11 构建一个可用于包装 C 函数的模板助手对象。
我正在尝试将给定 的答案从包装函数扩展到包装对象,以便它可以包含状态:
#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;
^
你在程序中没有指定 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>{}
完整的解决方案是here on Compiler Explorer。
它实际上只是@Dani 的解决方案和来自 的 C++11 模板详细信息的合并。
我想仅使用 C++11 构建一个可用于包装 C 函数的模板助手对象。
我正在尝试将给定
#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;
^
你在程序中没有指定 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>{}
完整的解决方案是here on Compiler Explorer。
它实际上只是@Dani 的解决方案和来自