使用自由函数作为伪构造函数来利用模板参数推导 [英] Using free function as pseudo-constructors to exploit template parameter deduction

查看:312
本文介绍了使用自由函数作为伪构造函数来利用模板参数推导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否使用自由函数作为伪构造函数来避免显式指定模板参数是一种常见模式/惯用法?

Is it a common pattern/idiom to use free functions as pseudo-constructors to avoid having to explicitly specify template parameters?

例如,每个人都知道 std :: make_pair ,它使用其参数来推导类型:

For example, everyone knows about std::make_pair, which uses its parameters to deduce the pair types:

template <class A, class B>
std::pair<A, B> make_pair(A a, B b)
{
  return std::pair<A, B>(a, b);
}

// This allows you to call make_pair(1, 2),
// instead of having to type pair<int, int>(1, 2)
// as you can't get type deduction from the constructor.

STL还在< functional> code>( bind1st not1 ptr_fun ,etc ...)

The STL also makes heavy use of this in <functional> (bind1st, not1, ptr_fun, etc...)

我发现自己经常使用,所以我只是想知道是否有很多其他人使用它,如果有一个名称为这种模式?

I find myself using this quite often, so I was just wondering if many other people use it, and if there is a name for this pattern?

推荐答案

显然它被称为对象生成器。请参见更多C ++成语Boost

Apparently it's called "Object Generator". See "More C++ Idioms" and "Boost" on this topic.

我个人认为它非常有用,它使用它。

I personally find it very useful and use it alot.

此外,我认为可能会看到表达式模板作为对象生成器的一种特殊形式,因为它们都是通过操作数类型和数据来构造复杂类型也手动指定。

Also, I think one might see expression templates as a special form of object generators, since all they do is construct complex types by means of operand types and data you normally could specify also manually. Except, they are calling the generators implicitly

a + b + c =>
  Add<Add<A, B>, C>(...)

这篇关于使用自由函数作为伪构造函数来利用模板参数推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆