开发者

C++: template params for a class but not a function [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

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

When calling a template function, you don't need to specify the template parameters if they are non-ambiguous from your 开发者_JS百科parameters. E.g. for:

template<typename T> T foo(T a) { /*...*/ }

You can just call foo(1) and it will work, it does not need to be foo<int>(1).

This is not true for classes/structs, even if it would be clear from the constructor parameters. For example:

template<typename T> struct Foo { Foo(T a) { /*...*/ } };

Now I cannot do just a do_something_with(Foo(1)), it must be do_something_with(Foo<int>(1)).

Often, to work around this issue, there are just some simple wrapper functions which basically just wrap the constructor. That is even in the STL: std::make_pair is such an example.

Now the question: Why is that? Is there any rational reason behind it?


As far as I know, function templates and class templates are different for the lulz and there's no real reason that they should be different from each other. Of course, class templates have partial specializations (T*) as an advantage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜