2014-01-08 111 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&'模式匹配时,所有的模板参数都被推导出来。 –

相关问题