mar*_*ark 1 c++ templates c++17
我有一个简单的包装模板,允许自由函数(例如open() close()等)作为模板参数传递。代码如下:
template <auto fn, typename ReturnType=void>
struct func_wrapper {
template<typename... Args>
constexpr ReturnType operator()(Args&&... args) const {
if constexpr( std::is_same<ReturnType, void>::value) {
fn(std::forward<Args>(args)...);
} else {
return fn(std::forward<Args>(args)...);
}
}
};
Run Code Online (Sandbox Code Playgroud)
其用法如下:
void CloseFunc2(int a);
into OpenFunc2(const std::string&, int flags);
using FileWrapper2 = DevFileWrapper<func_wrapper<OpenFunc2, int>,
func_wrapper<CloseFunc2>>;
Run Code Online (Sandbox Code Playgroud)
该代码工作正常,但我想删除ReturnType创建func_wrapper.
我尝试使用std::result_of但失败了,因为fn它是非类型模板参数,例如:
template<typename... Args>
constexpr auto operator()(Args&&... args) const
-> std::invoke_result<fn(std::forward<Args>(args)...)>::type {
if constexpr( std::is_same<ReturnType, void>::value) {
fn(std::forward<Args>(args)...);
} else {
return fn(std::forward<Args>(args)...);
}
}
Run Code Online (Sandbox Code Playgroud)
错误是:
template-parameter-callable.cpp:48:71: error: template argument for
template type parameter must be a type
constexpr auto operator()(Args&&... args) const ->
std::invoke_result<fn(std::forward<Args>(args)...)>::type {
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/
usr/include/c++/v1/type_traits:4009:17:
note: template parameter is declared here
template <class _Fn, class... _Args>
^
1 error generated.
Run Code Online (Sandbox Code Playgroud)
如何推断fn编译时调用的返回类型?
template <auto fn>
struct func_wrapper {
template<typename... Args>
constexpr decltype(auto) operator()(Args&&... args) const {
return fn(std::forward<Args>(args)...);
}
};
Run Code Online (Sandbox Code Playgroud)
你试过这个吗?
除非您还知道调用它所使用的参数,否则无法确定可调用对象的返回类型。
我可以提取返回类型,但我认为您不需要它。
template <auto fn>
struct func_wrapper {
template<typename... Args>
constexpr decltype(auto) operator()(Args&&... args) const {
using ReturnType = std::invoke_result_t<
decltype(fn),
Args&&...
>;
return fn(std::forward<Args>(args)...);
}
};
Run Code Online (Sandbox Code Playgroud)
但正如你所看到的,我们不需要它。
return f(x)当f退货void(现在)合法时。