I have written a simple class template:
template <class T>
class my_class
{
public:
my_class(T value)
: my_Value(value)
{
}
private:
T my_Value;
};
Now I can use this template in a simple function signature like: my_function(my_class<std::string> my_string)
When I want to call the function I can easily use it:
auto my_instance = my_class<std::string>("my value");
my_function(my_instance);
But what I want to realize is a function call like this:
my_function("my value")
My class template should implicit do the conversion to the type of the template for me. I think I need some kind of operator overload.
std:optional
can do this for example.
Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.
A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With