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);
};
CodePudding user response:
Deduction guide (c 17) might help:
template <std::size_t N>
Scalar(const char(&)[N]) -> Scalar<std::string>;
Demo.
CodePudding user response:
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