handle both string_view and wstring_view
-
Hallo,
ich habe eine Funktion, die am Besten für string und wstring (_view) gleichermaßen funktionieren soll (template):
Ich würde gerne wissen, ob ich hinbekomme dass auch ohne das '<char>' die Sache läuft. Ich kannte das bisher so, dass hier normal CharT vom Compiler herausgefunden wird.
#include <string> #include <string_view> template<class CharT> void doSomething(std::basic_string_view<CharT> str) { // .... } int main() { std::string s{"AAAA"}; doSomething<char>(s); // OK doSomething(s); // Sollte doch auch funktionieren? }
error: no matching function for call to 'doSomething(std::__cxx11::string&)' note: candidate: 'template<class CharT> void doSomething(std::basic_string_view<CharT>)' note: template argument deduction/substitution failed: note: 'std::__cxx11::basic_string<char>' is not derived from 'std::basic_string_view<CharT>'
Vielen Dank im Voraus!
-
Clang liefert folgende Fehlermeldung:
test.cpp:13:2: error: no matching function for call to 'doSomething' doSomething(s); // Sollte doch auch funktionieren? ^~~~~~~~~~~ test.cpp:5:6: note: candidate template ignored: could not match 'basic_string_view' against 'basic_string' void doSomething(std::basic_string_view<CharT> str) {
Nach der Fehlermeldung im internet gesucht und das hier gefunden:
"Implicit conversion is not a part of the template deduction process"
Quelle: https://www.reddit.com/r/cpp_questions/comments/6qvy4n/deduction_of_stdbasic_string_view/
-
Ich verstehe nicht warum die std::basic_string einen operator std::basic_string_view() geben, anstatt std::basic_string_view einen c-tor std::basic_string_view(const std::basic_string&); zu geben, wobei das vermutlich daran liegt, dass sich das mit den anderen c-tor beißt?
In dem Fall werde ich das nervige Problem umgehen:
template<class CharT> void doSomething_impl(std::basic_string_view<CharT> str) { // --- } void doSomething(std::string_view str) { return doSomething_impl(str); } void doSomething(std::wstring_view str) { return doSomething_impl(str); }