相关疑难解决方法(0)

模板推导功能?

我正在尝试编写一些模板函数,它们接受可以构造的a 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" });
}
Run Code Online (Sandbox Code Playgroud)

但这意味着对于每个函数,我都必须编写另一个调用第一个函数的函数。真烦人。有更简单的方法吗?也许它可能是模板推论指南,但据我所知,对于函数,仅对类不存在。

编译器不能推断:因为模板推演失败的第一个模板的功能是不够CharTstd::basic_string<CharT>,从CharT const *。这就是为什么我需要一种更简单的方法来告诉编译器的原因。

c++ templates argument-deduction c++17

4
推荐指数
2
解决办法
1082
查看次数

标签 统计

argument-deduction ×1

c++ ×1

c++17 ×1

templates ×1