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; }
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.
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.
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.
5. Which keyword is used for the template? Explanation: C++ uses template reserved keyword for defining templates.
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
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