c ++ 11具有函数默认参数值的可变参数args [英] c++11 variadic args with function default argument value

查看:35
本文介绍了c ++ 11具有函数默认参数值的可变参数args的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有调用模板函数 N 次的包装器:

I have wrapper that invokes template function N times:

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
}

一切正常,直到我使用默认参数传递函数:

Everything works fine until I pass function with default argument:

int f(int a, int b, int c = 5);
.... 
retry_n<10>(f, 1, 2); // error C2198: 'bla-bla' : too few arguments for call

如何允许在没有明确指定的情况下使用默认参数?

How to allow default argument be used without explicit specification?

推荐答案

默认参数不是函数签名的一部分,不参与模板类型推导.因此,每当您将 f 传递给 retry_n<> 时,F 的类型就会推导出为 int(int, int, int),所以本地的f属于后一种类型,默认参数不在此过程中.您唯一的解决方案是使用您想要直接测试的函数而不推导出其类型,例如@Johannes Schaub - litb 的注释,或者,如果您的编译器不支持通用 lambdas (C++14),请将其包装转换为带有可变参数模板的函子 operator()

A default parameter is not part of a function signature, and does not participate in template type deduction. So whenever you pass f to retry_n<>, the type of F is deduced as int(int, int, int), so the local f is of this latter type, and the default parameters is out of the process now. Your only solution is to use the function you want to test directly without having its type deduced, like in the comment of @Johannes Schaub - litb, or, if your compiler doesn't support generic lambdas (C++14), wrap it into a functor with a variadic template operator()

struct functor
{
    template<typename... T>
    int operator()(T&&... params)
    {
        return f(std::forward<T>(params)...);
    }  
};

并将其用作

retry_n<10>(functor{}, 1, 2);

这篇关于c ++ 11具有函数默认参数值的可变参数args的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆