[英]Variadic template function parameters and reference type deduction
我在這里缺少有關類型推斷的一些基本知識:
我試圖編寫一個包裝函數,該函數使用nullptr調用writer函數以獲取所需的長度,然后調整緩沖區的大小,然后再次調用該函數(現在具有調整后的緩沖區)以獲取最終輸出。 這些編寫器函數很多,我想將調用/調整大小/調用模式歸納為可變參數模板函數。
但是,當列表中的任何參數是const引用時,我都會嘗試將函數指針傳遞給采用可變參數args的函數,並傳遞可變參數args:
static void val_arg(int) { }
static void ref_arg(const int&) { }
template <typename... Args>
static void helper(void (*fun)(Args...), Args... args)
{
(*fun)(args...);
}
void proxy(const int& arg)
{
helper(&val_arg, arg); // Fine
helper(&ref_arg, arg); // 'void helper(void (__cdecl *)(Args...),Args...)': template parameter 'Args' is ambiguous
// note: could be 'const int&'
// note: or 'int'
}
void test()
{
proxy(1); // Force 1 to be const int&
}
如何使它透明地接受這兩種情況? 為什么不承認傳入的函數接受const ref,並且代理的參數也是const ref?
Args...
不會推斷出引用類型。
template <typename Fun, typename... Args>
static void helper(Fun fun, Args&&... args)
{
fun(std::forward<Args>(args)...);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.