我正在尝试编写一些模板函数,可以接受std::basic_string
或char数组,从中构建出basic_string
。
我的当前解决方案是:
#include <string>
template<typename CharT>
void foo(std::basic_string<CharT> str)
{
(void)str; // do something with str
}
template<typename CharT>
void foo(CharT const * arr)
{
return foo(std::basic_string<CharT>{arr});
}
int main(void)
{
foo("hello");
foo(std::string{ "hello" });
foo(L"hello");
foo(std::wstring{ L"hello" });
}
但这意味着对于每个函数,我都需要编写另一个调用第一个函数的函数。这很烦人;有没有更简单的方法?也许可以使用模板推导指南,但据我所知,它不存在于函数中,只存在于类中。
第一个模板函数不足够,因为模板推导失败:编译器无法从CharT const *
中推导出std::basic_string<CharT>
中的CharT
。这就是为什么我需要一种更简单的方法来告诉编译器。
template<typename CharT> void foo(std::basic_string_view<CharT> str)
? - ildjarnCharT const *
版本时,我只想构建一个 basic_string 并像示例中那样调用第一个版本。当这不是一个模板函数时,一切都是隐式的,但在这里编译器不会从char const *
构建一个basic_string <char>
,因为推导失败了。 - Boiethios