2013-03-08 37 views
4

我遇到了C++模板難題。我試圖把它縮小到最低限度,現在我甚至不確定我想要做什麼是可能的。看看下面的代碼(在一些.h文件中)。模板難題

template<typename T> 
class A 
{ 
public: 
    template<typename S> 
    void f(S x); 
}; 

class B1 { }; 

template<typename S> 
class B2 { }; 

//This one works: 
template<> 
template<typename S> 
void A<B1>::f(S x) 
{ 
}  

//This one does not work: 
template<> 
template<typename S> 
void A<B2<S>>::f(S x) 
{ 
} 

在我main功能我有這樣的事情:

//This one works: 
A<B1> first; 
first.f<int>(5); 

//This one does not work: 
A<B2<int>> second; 
second.f<int>(5); 

錯誤消息我得到的,因爲第二部分是

error C3860: template argument list following class 
      template name must list parameters in the 
      order used in template parameter list 

error C3855: 'A<T>': template parameter 'T' is 
      incompatible with the declaration 

任何想法的問題是什麼?


編輯

爲了使問題更具體,這裏是我的動力。我希望上述功能f針對T=std::tuple<T1, T2>,T=std::tuple<T1, T2, T3>T=std::tuple<T1, T2, T3, T4>進行專業化,其中tuple中的類型仍未綁定。

+1

你想用這個做什麼?也許有更好的方法。 – Pubby 2013-03-08 19:47:07

+0

這是你想要的嗎? http://stacked-crooked.com/view?id=8b9365eab6441615b312ad76b0500bb7-18aa934a8d82d638dde2147aa94cac94 – Pubby 2013-03-08 19:53:28

+0

@Pubby我在動機的最後加了一段。 – 2013-03-08 20:05:35

回答

4

您試圖部分專門化成員函數模板。這是不可能的,恐怕...

1

如果你想另一個模板傳遞給模板,你必須使用template template parameters,讓你的A <>模板應該是這樣的:

template<typename T> 
class A 
{ 
public: 
    template<template <typename> class H, typename S> 
    void f(H<S> x); 
}; 

現在,你可以通過一個模板到您的模板。

我不認爲你可以專注於模板模板參數,如果你的原始模板沒有采取這樣的參數類型。

+2

我不這麼認爲。他希望'int'也能工作。 – Pubby 2013-03-08 19:47:43

+0

我現在正在研究這個問題......將回復您是否適用於我。看起來很有希望。 – 2013-03-08 19:52:42

3

你的代碼有兩個問題。首先,第二專業化是非法的,因爲

template<> // parameters useable for the specialization of A you refer to 
      // since it is a function, no partial specialization is allowed. 
template<typename S> // parameters for the function's parameters 
void A<B2<S>>   // S can not be used here! 
      ::f(S x) // only here 
{ 
} 

如果我改變,要

template<> 
template<typename S> 
void A<B2<int>>::f(S x) 
{ 
} 

它的工作原理,現在第二個問題暴露:

second.f<B2<int>>(5); 

這臺SB2<int>並且函數期望參數S x - 但整數5不能轉換爲該類型。將其更改爲:

B2<int> x; 
second.f<B2<int>>(x); 

它也適用。

請注意,這可能無法解決您試圖解決的問題,它只是解釋發生了什麼。


思考你的編輯:我認爲你嘗試專門爲T=std::tuple<...>事實已經指明瞭方向:TA模板參數和是你應該專注什麼。可能是這樣的:

template< typename T > 
class F // used to implement f(), so you can specialize 
     // just F/f() instead of the whole class A 
{ 
    void f(T x) { /* default impl */ } 
}; 

template< typename T1, typename T2 > 
class F< std::tuple< T1, T2 > > 
{ 
    void f(T1 x, T2 y) { /* special impl */ } 
}; 

template< typename T > 
class A : public F<T> 
{ 
    // ...other stuff... 
};