Why is that automatic type deduction is possible only for functions and not for Classes?
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
The difference is, that the compiler does type checking before template expansion. The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of the same function/class. Function Templates We write a generic function that can be used for different data types.
An individual class defines how a group of objects can be constructed, while a class template defines how a group of classes can be generated. Note the distinction between the terms class template and template class: Class template. is a template used to generate template classes.
Template argument deduction is used in declarations of functions, when deducing the meaning of the auto specifier in the function's return type, from the return statement.
In specific cases you could always do like std::make_pair
:
template<class T>
make_foo(T val) {
return foo<T>(val);
}
EDIT: I just found the following in "The C++ Programming Language, Third Edition", page 335. Bjarne says:
Note that class template arguments are never deduced. The reason is that the flexibility provided by several constructors for a class would make such deduction impossible in many cases and obscure in many more.
This is of course very subjective. There's been some discussion about this in comp.std.c++
and the consensus seems to be that there's no reason why it couldn't be supported. Whether it would be a good idea or not is another question...
At Kona meeting Template parameter deduction for constructors (P0091R0) has been approved, which means that in C++17 we'll be able to we can write:
pair p1{"foo"s, 12};
auto p2 = pair{"foo"s, 12};
f(pair{"foo"s, 12});
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