這是一個常見問題,但我找不到滿意的答案。在我的項目中,我們支持std::string
,現在還必須支持寬字符串。因此,我們要搬到basic_string
,但隨後,事情停止工作很好和參數需要被明確地闡明:basic_string <CharT>與CharT *
#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");
}
OK,它失敗了著名的理由:
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'的xplicit版本與clang3.5一起工作,只有帶參數推演的版本(最後一行)失敗,因爲它無法推導出參數。 – Drax 2014-10-27 15:55:02