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

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

问题描述

是否使用免费函数作为伪构造函数来避免必须明确指定模板参数的常见模式/成语?

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> 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亲自发现它非常有用,并且使用它很多。

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天全站免登陆