4 c++ templates std-function template-argument-deduction c++17
我正在研究类似下面的代码
#include <functional>
template <typename Type>
void foo(const std::function<void(const Type&)> & handler) {}
void goo (const int&){}
int main() {
foo([](const int&){});
foo(goo);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,由于跟随错误,它拒绝编译(clang 6.0.0和gcc 8.1.1)
candidate template ignored: could not match 'function<void (const type-parameter-0-0 &)>' against '(lambda at test3.cpp:13:9)'
candidate template ignored: could not match 'function<void (const type-parameter-0-0 &)>' against '(lambda at test3.cpp:13:9)'
Run Code Online (Sandbox Code Playgroud)
有可能以某种方式迫使它Type
正确演绎吗?
你标记了C++ 17,所以你可以使用演绎指南std::function
.
您可以尝试以下方法
template <typename F,
typename Type = typename decltype(std::function{std::declval<F>()})::argument_type>
void foo (F f)
{
}
Run Code Online (Sandbox Code Playgroud)
我知道argument_type
在C++ 17中已弃用,但您可以用简单的自定义模板替换它.
以身作则
template <typename>
struct firstArg;
template <typename R, typename A0, typename ... As>
struct firstArg<std::function<R(A0, As...)>>
{ using type = A0; };
Run Code Online (Sandbox Code Playgroud)
并且foo()
可以写成
template <typename F,
typename FUNC = decltype(std::function{std::declval<F>()}),
typename Type = typename firstArg<FUNC>::type>
void foo (F f)
{
}
Run Code Online (Sandbox Code Playgroud)
这样,callable f
不是一个std::function
但它是原始类型(根据你的确切要求,这可能更好或更差); 如果你需要它std::function
,你可以foo()
使用再次扣除指南或FUNC
类型在函数内获得它
template <typename F,
typename FUNC = decltype(std::function{std::declval<F>()}),
typename Type = typename firstArg<FUNC>::type>
void foo (F f)
{
FUNC fnc{f};
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
217 次 |
最近记录: |