2011-10-22 63 views
1

我有一個處理管線實現,但我想提高它像這樣:爲什麼這個帶有可變參數模板參數的構造函數不匹配?

#include <iostream> 

// buffers 
struct src{}; struct b1{}; struct snk{}; 
// filters 
struct f1 
{ 
    f1(const src &, b1 &) { std::cout << "f1(src, b1)" << std::endl; } 
}; 
struct f2 
{ 
    f2(const b1 &, snk &) { std::cout << "f2(b1, snk)" << std::endl; } 
}; 
// the pipeline 
template< typename... Filters > 
struct pipeline 
{ 
    template< typename LastB > 
    pipeline(const LastB &) 
    {} 
}; 
template < typename T1, typename... T > 
struct pipeline< T1, T... > : pipeline<T...> 
{ 
    template< typename... Buffs, typename Bin, typename Bout > 
    pipeline(Buffs &... buffs, Bin & bin, Bout & bout) : 
     pipeline<T...>(buffs..., bin), 
     filter(bin, bout) 
    { 
    } 

    T1 filter; 
}; 

int main() 
{ 
    src ba; b1 bb; snk bc; 

    pipeline<f1> p1(ba, bb); 
    pipeline< f1, f2 > p2(ba, bb, bc); // the problem is in this line! 
} 

不幸的是,上面的例子中產生下一個錯誤:

sda_variadic.cpp: In function 'int main()': 
sda_variadic.cpp:40:39: error: no matching function for call to 'pipeline<f1, f2>::pipeline(src&, b1&, snk&)' 
sda_variadic.cpp:40:39: note: candidates are: 
sda_variadic.cpp:26:5: note: template<class ... Buffs, class Bin, class Bout> pipeline<T1, T ...>::pipeline(Buffs& ..., Bin&, Bout&) 
sda_variadic.cpp:23:8: note: constexpr pipeline<f1, f2>::pipeline(const pipeline<f1, f2>&) 
sda_variadic.cpp:23:8: note: candidate expects 1 argument, 3 provided 
sda_variadic.cpp:23:8: note: constexpr pipeline<f1, f2>::pipeline(pipeline<f1, f2>&&) 
sda_variadic.cpp:23:8: note: candidate expects 1 argument, 3 provided 

,這是什麼錯誤的原因是什麼?
如何解決它?

只是一個小小的解釋。我期望上面的例子將首先創建未專門化的對象pipeline<>(snk),然後專用對象pipeline<f1>(b1,snk),然後專門對象pipeline< f1, f2 >(src,b1,snk)
順便說一句,上面的例子適用於1個過濾器(pipeline< f1)。

回答

4
template< typename... Buffs, typename Bin, typename Bout > 
pipeline(Buffs &... buffs, Bin & bin, Bout & bout) : 
    pipeline<T...>(buffs..., bin), 
    filter(bin, bout) 
{ 
} 

由於函數參數包(Buffs)不是最後一個位置,它不能被推導出來。從14.8.2.1推導模板參數從一個函數調用[temp.deduct.call]第1款規定:

  1. [...]對於沒有在參數 - 年底發生的函數參數包聲明列表中,參數包的類型是非推導的上下文。 [...]

既然你不能明確地傳遞模板參數構造函數,它不能在全稱爲(不是說有什麼關係你的問題雖然)。

我建議使用std::tuple來操縱可變參數,以便像這樣調用構造函數:pipeline(std::forward_as_tuple(b0, b1, b2), in, out)並將空元組傳遞給最後一個階段。

相關問題