Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function call with template parameter

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.

like image 923
Dirk Avatar asked Dec 10 '20 12:12

Dirk


People also ask

How do you call a function in a template?

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.

Can a template parameter be a function?

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.

Which is correct example of template parameters?

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.

How do you use template arguments in C++?

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


1 Answers

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)
like image 69
Jarod42 Avatar answered Sep 22 '22 14:09

Jarod42