Function call with template parameter
You can have only one implicit user-conversion, so your call with const char*
is invalid.
There are several options,
add another constructor for my_class
my_class(T value) : my_Value(value) {} template <typename U, std::enable_if_t<std::is_convertible<U, T>, int> = 0> my_class(U value) : my_Value(value) {}
add overload for my_function,
void my_function(my_class<std::string> my_string) void my_function(const char* s) { return my_function(my_class<std::string>{s}); }
change call site to call it with
std::string
:my_function(std::string("my value")) using namespace std::string_literals; my_function("my value"s)
You have to add constructor accepting type convertible to your T
.
The "classic" pre-C++20 way is to use SFINAE and std::enable_if
:
template <typename T>
class my_class
{
public:
template <typename U, typename = std::enable_if_t<std::is_constructible_v<T,U>>>
my_class(U&& arg) : my_Value(std::forward<U>(arg))
{}
...
Demo
With newest standard (C++20) you can use concepts and simplify your code:
template <typename T>
class my_class
{
public:
template <typename U>
my_class(U&& arg) requires(std::is_constructible_v<T,U>)
: my_Value(std::forward<U>(arg))
{}
...
Or even simpler:
template <typename T, typename U>
concept constructible_to = std::constructible_from<U, T>;
template <typename T>
class my_class
{
public:
template <constructible_to<T> U>
my_class(U&& arg)
: my_Value(std::forward<U>(arg))
{}
...