1

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);

};
1
  • @MarekR I am porting a library that I didn't write myself from Python to C++. I'd like that the Python and C++ code look, except from low-level classes, such as this one, more or less the same. Commented Jun 6, 2022 at 14:59

2 Answers 2

7

Deduction guide (c++17) might help:

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

Demo.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.