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

后端 未结 4 2063
难免孤独
难免孤独 2020-12-03 01:37

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

4条回答
  •  生来不讨喜
    2020-12-03 02:40

    In specific cases you could always do like std::make_pair:

    template
    make_foo(T val) {
        return foo(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...

提交回复
热议问题