强迫字符串文字参数导致std ::字符串类模板扣除
我想编写一个类模板,该模板能够容纳不同的类型。但是,我想避免类型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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“ noreferrer”>扣除指南(c ++ 17)可能会有所帮助:
demo 。
Deduction guide (c++17) might help:
Demo.
另一个解决方案是使用 std :: string_literals :
当然,使用应该已经意识到使用文字
“ s
将字符串字符级转换为
std :: String
Another solution is to use std::string_literals:
Of course, the use should already be aware to use the literal
"s
to convert the string-literal to
std::string