2014-01-08 112 views
0

我的問題的條紋下來的版本:無法推斷出模板參數與標準:: basic_string的

我要合併這兩個功能:

void Bar(const std::string &s); 
void Bar(const std::wstring &s); 

..into一個模板函數:

template <class CharType> 
void Foo(const std::basic_string<CharType> &s); 

而且我認爲我將能夠調用Foo(1)(2),但甚至沒有(3)讓我吃驚作品。

(1) Foo("my string"); 
(2) Foo(std::string("my string")); 
(3) Foo(std::basic_string<char>("my string")); 

我試圖爲參數s除去const限定符和甚至滴加​​參考(&),或與lvalues代替rvalues調用,但都具有相同的結果。

編譯器(包括gcc和VS--所以我敢肯定它是標準兼容行爲)不能推導出Foo的模板參數。當然,如果我撥打Foo(如Foo<char>(...)),它就可以工作。

所以我想明白這是爲什麼,尤其是因爲調用(3)是調用參數對象類型和函數參數類型之間的一對一類型。

其次,我想要一個解決方法:能夠使用一個模板化功能,並能夠稱爲它像(1)(2)

編輯

(2)(3)做的工作。我在我的編譯器中聲明它是錯誤的(不像我的問題):

template <class CharType> 
    void Foo(const std::basic_string<char> &s); 

對不起。

+0

據我可以看到在VS的實現'std :: string'不是真的'basic_string '是'basic_string ,'分配器>'所以我認爲它不工作,因爲它缺少一些模板參數。 – Raxvan

+0

編輯我的答案,現在可能適合您的需求 –

回答

3

因爲你想使用爲const char [10]代替的std :: string

2)應該工作,所以應該3)因爲默認的模板參數應該包括:1)將無法正常工作確保您使用默認值

#include <iostream> 
using namespace std; 

template <class CharType> 
void Foo(const std::basic_string<CharType> &s) 
{ 
    cout << s.c_str(); // TODO: Handle cout for wstring!!! 
} 

void Foo(const char *s) 
{ 
    Foo((std::string)s); 
} 

int main() 
{ 
    std::wstring mystr(L"hello"); 
    Foo(mystr); 

    Foo("world"); 

    Foo(std::string("Im")); 

    Foo(std::basic_string<char>("so happy")); 

    return 0; 
} 

http://ideone.com/L63Gkn

與模板參數打交道時小心。我還爲wstring提供了一個小的重載,看看是否適合你。

+0

上帝,我宣佈它像'template void Foo(const std :: basic_string &s)''。我將編輯我的問題。謝謝。 – bolov

+0

沒關係,我不使用我的函數寫入流。在我的真實函數中,我有更多的字符串參數,並生成並返回一個新的字符串。 – bolov

3

基本字符串模板的樣子:

template< 
    class CharT, 
    class Traits = std::char_traits<CharT>, 
    class Allocator = std::allocator<CharT> 
> class basic_string; 

,所以你需要聲明你的功能

template <typename CharType, typename CharTrait, typename Allocator> 
void Foo(const std::basic_string<CharType, CharTrait, Allocator> &s); 

它匹配(所有的模板類型參數可以推斷出,所以我不認爲你不需要在你的函數中複製默認值)。

+0

我確認複製函數中的默認值是無用的;當推論出's'參數與'std :: basic_string <...> const&'模式匹配時,所有的模板參數都被推導出來。 –

相關問題