【发布时间】:2014-12-22 20:33:51
【问题描述】:
这是一个常见问题解答,但我找不到令人满意的答案。在我的项目中,我们支持std::string,现在还必须支持宽字符串。所以我们想转移到basic_string,但随后,事情就停止了,需要明确说明参数:
#include <string>
template <typename CharT, typename Traits, typename Allocator>
void
foo(const std::basic_string<CharT, Traits, Allocator>&)
{}
template void foo(const std::string&);
// template void
// foo<char, std::char_traits<char>, std::allocator<char>>(const std::string&);
void bar(const std::string& s)
{}
int main()
{
bar("abc");
foo<char, std::char_traits<char>, std::allocator<char>>("def");
foo("def");
}
好的,众所周知的原因它失败了:
clang++-mp-3.5 -Wall -std=c++11 foo.cc
foo.cc:20:3: error: no matching function for call to 'foo'
foo("def");
^~~
foo.cc:5:1: note: candidate template ignored: could not match
'basic_string<type-parameter-0-0, type-parameter-0-1, type-parameter-0-2>'
against 'char const[4]'
foo(const std::basic_string<CharT, Traits, Allocator>&)
^
我不明白为什么它适用于bar?为什么 foo 对 char 的显式实例化(使用显式模板参数或使用推导)不足以解决此问题?
这似乎意味着我们将不得不将其用作实现细节,而不是在公开的 API 中使用模板和 basic_string,但向用户公开 std::string、std::wstring 等的重载。真可惜。
谢谢!
【问题讨论】:
-
foo的显式版本与clang3.5一起工作,只有带参数推导失败(最后一行),因为它不能推导参数。
标签: c++ templates c++11 type-deduction stdstring