强迫字符串文字参数导致std ::字符串类模板扣除

发布于 2025-02-04 15:41:26 字数 533 浏览 2 评论 0原文

我想编写一个类模板,该模板能够容纳不同的类型。但是,我想避免类型char*char []的专业。字符字符串应始终为std :: String。下面的代码是我到目前为止所拥有的。但是,编写标量(“ Hello”)产生t = char [6],而不是t = std :: String。我可以编写scalar< std :: string>(“ hello”)scalar(std :: string(“ hello”))以解决问题。我的问题是,是否有一种方法可以修改下面的代码,以便编写标量(“ Hello”)按预期工作,并且类仍然只有一个模板参数?

template <typename T>
class Scalar {
public:

explicit Scalar(const T& val);

};

I would like to write a class template, which is able to hold different types. However, I want to avoid specializations of type char* or char[]. Character strings should always be std::string. The code below is what I have so far. However, writing Scalar("hello") yields T = char[6] and not T = std::string. I could write Scalar<std::string>("hello") or Scalar(std::string("hello")) to work around the problem. My question is, is there a way to modify the code below such that writing Scalar("hello") works as intended and the class still has only one template parameter?

template <typename T>
class Scalar {
public:

explicit Scalar(const T& val);

};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

妳是的陽光 2025-02-11 15:41:26

“ noreferrer”>扣除指南(c ++ 17)可能会有所帮助:

template <std::size_t N>
Scalar(const char(&)[N]) -> Scalar<std::string>;

demo

Deduction guide (c++17) might help:

template <std::size_t N>
Scalar(const char(&)[N]) -> Scalar<std::string>;

Demo.

萤火眠眠 2025-02-11 15:41:26

另一个解决方案是使用 std :: string_literals

#include <string>

template <typename T>
class Scalar {
public:
    explicit Scalar(const T& val) {}
};

int main()
{
   using namespace std::string_literals;    
   Scalar test("hello"s);
}

当然,使用应该已经意识到使用文字“ s
将字符串字符级转换为std :: String

Another solution is to use std::string_literals:

#include <string>

template <typename T>
class Scalar {
public:
    explicit Scalar(const T& val) {}
};

int main()
{
   using namespace std::string_literals;    
   Scalar test("hello"s);
}

Of course, the use should already be aware to use the literal "s
to convert the string-literal to std::string

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文