Dew*_*wfy 5 variadic-templates c++11
我有包装器调用模板函数N次:
template <std::uint16_t N, typename F, typename ... Args>
inline typename std::result_of<F && (Args &&...)>::type retry_n(F && f, Args&& ... ax)
{
for (auto i = 0; i < N; ++i)
{
try
{
return std::forward<F>(f)(std::forward<Args>(ax)...);
}
catch (const some_except &e){ /*ignore exception for a while*/ }
}
throw;//re-raise
}
Run Code Online (Sandbox Code Playgroud)
一切正常,直到我使用默认参数传递函数:
int f(int a, int b, int c = 5);
....
retry_n<10>(f, 1, 2); // error C2198: 'bla-bla' : too few arguments for call
Run Code Online (Sandbox Code Playgroud)
如何在没有明确规范的情况下使用默认参数?
默认参数不是函数签名的一部分,也不参与模板类型推导。因此,每当您传递f给 时retry_n<>, 的类型F都会被推导为int(int, int, int),因此本地f是后一种类型,并且默认参数现在不在进程中。您唯一的解决方案是直接使用您想要测试的函数,而不推导其类型,就像@Johannes Schaub - litb 的评论中一样,或者,如果您的编译器不支持通用 lambda (C++14),请将其包装起来变成带有可变参数模板的函子operator()
struct functor
{
template<typename... T>
int operator()(T&&... params)
{
return f(std::forward<T>(params)...);
}
};
Run Code Online (Sandbox Code Playgroud)
并将其用作
retry_n<10>(functor{}, 1, 2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
484 次 |
| 最近记录: |