【问题标题】:Could not deduce template argument with std::basic_string无法用 std::basic_string 推断模板参数
【发布时间】:2014-01-08 14:01:57
【问题描述】:

我的问题的精简版:

我想合并这两个函数:

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

..集成到一个模板函数中:

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

我认为我可以像(1)(2) 一样调用Foo,但令我惊讶的是,甚至(3) 都不起作用。

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

我尝试删除参数 sconst 限定符,甚至删除引用 (&amp;),或者使用 lvalues 而不是 rvalues 调用,但结果相同。

编译器(gcc 和 VS - 所以我很确定这是符合标准的行为)无法推断出 Foo 的模板参数。当然,如果我像Foo&lt;char&gt;(...) 一样调用Foo,它会起作用。

所以我想了解这是为什么,特别是因为调用(3)是调用参数对象的类型和函数参数类型之间的一对一类型。

其次,我想要一个解决方法:能够使用一个模板函数,并且能够像 (1)(2) 一样调用它。

编辑

(2)(3) 工作。我在我的编译器中声明它是错误的(不像我的问题):

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

对此感到抱歉。

【问题讨论】:

  • 据我在 VS 的实现中所见,std::string 并不是真正的basic_string&lt;char&gt;basic_string&lt;char,char_traits&lt;char&gt;,allocator&lt;char&gt; &gt;,所以我认为它不起作用,因为它缺少一些模板参数。
  • 编辑了我的答案,现在可能适合您的需求
  • 请注意,您不需要像那样将类型分开。使用template&lt;class StringT&gt; void Foo(StringT const &amp; s) ... 的工作方式相同,并允许std::basic_string&lt;&gt; 以外的字符串类型。不幸的是,这对案例 (1) 没有帮助。

标签: c++ templates template-argument-deduction


【解决方案1】:

1) 不起作用,因为您尝试使用 const char[10] 而不是 std::string

2) 应该可以工作,3) 因为默认模板参数应该确保您使用默认值

#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 提供了一个小的重载,看看是否适合你。

【讨论】:

  • 天哪,我像 template &lt;class CharType&gt; void Foo(const std::basic_string&lt;char&gt; &amp;s) 一样声明它。我将编辑我的问题。谢谢。
  • 没关系,我不使用我的函数写入流。在我的真实函数中,我有更多字符串参数,我生成并返回一个新字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多