Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template type deduction in C++ for Class vs Function?

Why is that automatic type deduction is possible only for functions and not for Classes?

like image 800
yesraaj Avatar asked Dec 17 '09 13:12

yesraaj


People also ask

What is the difference between function and class template?

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.

Is class template and function template the same?

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.

What is the difference between class template and template class?

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.

What is template argument deduction?

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.


2 Answers

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

like image 123
Andreas Brinck Avatar answered Oct 01 '22 04:10

Andreas Brinck


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});
like image 38
bolov Avatar answered Oct 01 '22 03:10

bolov