Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call the right constructor of a template type?

Tags:

In the following code, how can I make the commented line working in the same way as the line just above of it?

I would like to make it a generic code, that call suitable constructor of a template Type.

#include <string> #include <iostream>  template <typename Type> struct Class {     Type data;     Class(Type data) : data(data) { } };  int main() {     Class<std::string> a = std::string("abc");     // Class<std::string> b = "abc";     std::cout << a.data << std::endl;     return 0; } 
like image 346
no one special Avatar asked Dec 24 '19 13:12

no one special


People also ask

Can you template a constructor?

As long as you are satisfied with automatic type inference, you can use a template constructor (of a non-template class). @updogliu: Absolutely. But, the question is asking about "a template constructor with no arguments" If there are no function arguments, no template arguments may be deduced.

Can copy constructor be template?

The copy constructor lets you create a new object from an existing one by initialization. A copy constructor of a class A is a non-template constructor in which the first parameter is of type A& , const A& , volatile A& , or const volatile A& , and the rest of its parameters (if there are any) have default values.

What is template name the type of template?

Technical overview. There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic.

Which keyword is used to define template?

5. Which keyword is used for the template? Explanation: C++ uses template reserved keyword for defining templates.


1 Answers

Use braced-init-list(or uniform-initiation) to initlize the instance of Class.

Class<std::string> a{ std::string("abc") };  // works Class<std::string> b{ "abc" };               // also works 
like image 135
JeJo Avatar answered Sep 27 '22 17:09

JeJo