Force implicit conversion of a string literal in templated class?

The code below doesn't compile because string literal instead of std::string is given to constructor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <string>
#include <type_traits>

template<typename StringType>
requires std::is_same_v<StringType, std::wstring> || std::is_same_v<StringType, std::string>
class Exception
{
public:
	Exception(StringType message)
	{
	}
};

int main()
{
	// Make it implicitly convert to std::string?
	Exception test("string literal");
	return 0;
}


Is there anything we can do to make it work without saying Exception test(std::string("string literal"));

Another option is to say Exception<std::string> test("string literal");
But I would like to to avoid this if possible and make it default somehow.
Last edited on
Add deduction guides following the class definition (line 13):
1
2
Exception(char const*) -> Exception<std::string>; 
Exception(wchar_t const*) -> Exception<std::wstring>;

https://en.cppreference.com/w/cpp/language/class_template_argument_deduction
Awesome, thanks a bunch!

Since which cpp version is this syntax introduced?
Topic archived. No new replies allowed.