【解決方法】basic_string を関数に渡す方法 "…" タイプ

プログラミングQA


以下の C++ 20 コードを参照してください。 関数 foo の引数として basic_string を受け入れようとしているだけです。 L”…” 型を使用しようとすると、コンパイル エラーが発生します。 ただし、 L”…” 型からローカルの wstring 型変数を構築することは可能です。 なぜこれは矛盾していないのですか? ローカル変数がそのように構築できる場合、関数 foo の引数ではないのはなぜですか。 typeid().name() で示される “…” の型は charType です[number of characters] これは、私があまり知識も経験も持っていない配列であると思います。 cppreference.com の basic_string コンストラクターのドキュメントには、サポートされている配列が表示されていないため、ローカル変数をこの型から構築する必要がある理由がわかりません。 ドキュメントは StringViewLike と呼ばれるものを参照していますが、このタイプの経験はありませんが、そのコンストラクターのドキュメントでは配列タイプについても言及されていません。 よろしく

C++
#include <string>
#include <iostream>
using namespace std;

template<typename charType>
void foo(basic_string<charType> _basic_string);

int main()
{
	wstring _wstring_a(L"aaa");  // okeedokee
	wstring _wstring_b = L"bbb"; // okeedokee

	foo(L"abc"); // error below
#ifdef _UNDEFINED_
	error C2672 : 'foo' : no matching overloaded function found
		message : could be 'void foo(std::basic_string<_Elem,std::char_traits<_Elem>,std::allocator<_Ty>>)'
		message : 'void foo(std::basic_string<_Elem,std::char_traits<_Elem>,std::allocator<_Ty>>)' : could not deduce template argument for 'std::basic_string<_Elem,std::char_traits<_Elem>,std::allocator<_Ty>>' from 'const wchar_t [4]'
#endif
		return 0;
}

もちろん、たとえば foo(wstring(L”text going here”)) などのすべての引数を渡すことができますが、 wstring を明示的に呼び出す必要があるとは思いません。

私が試したこと:

cppreference.com で basic_string コンストラクターのドキュメントを参照してください。

解決策 1

回避策:

C++
#include <iostream>
using namespace std;

template<typename charType>
void foo(basic_string<charType> _basic_string)
{
  std::cout << "string\n";
}

template <typename charType>
void foo(const charType * pct)
{
  std::cout << "pointer, ";
  foo( basic_string<charType>{pct});
}


int main()
{
  foo(wstring{L"Hello"});
  foo(L"World!");
}

コメント

タイトルとURLをコピーしました