views:

181

answers:

3

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

A: 

I think implicit type conversion is only applicable to function arguments only so compiler can deduce it to make the function call success.

But how can it deduce what type you wanna have it class.

We have to wait 4 such a day when we have AI based compiler to do read our minds.

Ashish
-1 As far as I know, psychic powers are not part of any AI research program. Plus, while I recognize that English is not everyone's first language, the abuse of '4' is unforgivable.
Dan Hook
+6  A: 

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

Andreas Brinck
That is what I am asking why would you need to wrap a class inside a function, as like they do in boost::bind
yesraaj
The flexibility provided by several constructors is no less or more than the flexibility provided by several overloads.
DeadMG
+2  A: 

In case of a function call, the compiler deduces the template type from the argument type. For example the std::max-function. The compiler uses the type of the arguments to deduce the template parameter. This does not allways work, as not all calls are unambigous.

int a = 5;
float b = 10;

double result1 = std::min( a, b ); // error: template parameter ambigous
double result2 = std::min< double >( a, b ); // explicit parameter enforces use of conversion

In case of a template class, that may not allways be possible. Take for instance this class:

template< class T>
class Foo {
public:
    Foo();
    void Bar( int a );
private:
    T m_Member;
};

The type T never appears in any function call, so the compiler has no hint at all, what type should be used.

Space_C0wb0y
So it's not always possible, but, as you point out, neither is it for functions. So that doesn't really explain why it isn't supported.
jon hanson
I do not know why it is not supported (a best-effort-solution would be conceivable), but the question was, if it is possible. I think i answered that, so I do not understand the downvote.
Space_C0wb0y
I think he asked *why* it's not possible, not *whether* it's possible.
Johannes Schaub - litb