暧昧超载访问参数少模板函数与可变参数的参数 [英] Ambiguous overload accessing argument-less template functions with variadic parameters

查看:173
本文介绍了暧昧超载访问参数少模板函数与可变参数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

呀,标题可以吓唬宝宝,但它实际上是非常简单的。

Yeah, the title can scare babies, but it's actually quite straightforward.

我想一个函数指针存储到一个专门的模板功能,即提高:: make_shared(1.41提振),如下图:

I am trying to store a function pointer to a specialized template function, namely boost::make_shared (boost 1.41), as illustrated:

boost::shared_ptr<int> (*pt2Function)() = boost::make_shared<int>;

但是,它不会编译(GCC 4.4.1)由于事实的boost :: make_shared有以下两个专业在这个背景下,编译器不能分辨:

However, it won't compile (GCC 4.4.1) due to the fact that boost::make_shared has the following two specializations which the compiler can't tell apart in this context:

template< class T > boost::shared_ptr< T > make_shared()
...
template< class T, class... Args > boost::shared_ptr< T > make_shared( Args && ... args )

该错误,以供参考:

The error, for reference:

In function ‘int main()’:
error: converting overloaded function ‘make_shared’ to type ‘class boost::shared_ptr<int> (*)()’ is ambiguous
boost/smart_ptr/make_shared.hpp:100: error: candidates are: boost::shared_ptr<X> boost::make_shared() [with T = int]
boost/smart_ptr/make_shared.hpp:138: error:                 boost::shared_ptr<X> boost::make_shared(Args&& ...) [with T = int, Args = ]

如果我注释掉非可变参数的变化,在code编译罚款。

If I comment out the non-variadic variation, the code compiles fine.

有谁知道正确的语法像这样解决双参数较少功能之间的歧义?

Does anyone know the proper syntax for resolving the ambiguity between two argument-less functions like this?

推荐答案

可变参数模板参数表示你的 0到n 的模板参数,因此,不论你的版本匹配。结果
你可以通过添加另外一个模板参数的第二个版本解决的模糊性,所以它需要的 1..1 的参数。结果
像这样的东西应该工作:

Variadic template arguments mean you take 0..n template arguments, thus both your versions are matches.
You could resolve the ambiguity by adding another template parameter to the second version, so that it takes 1..n arguments.
Something like this should work:

template< class T, class Arg1, class... Args > 
boost::shared_ptr< T > make_shared(Arg1&& arg1, Args && ... args )

但作为UncleBens正确地指出的那样,你甚至不需要两个版本。下面应该足够你的情况:

But as UncleBens correctly pointed out, you don't even need two versions. The following should be enough in your case:

template< class T, class... Args > 
boost::shared_ptr<T> make_shared(Args && ... args );

如果你只使用一个模板参数(即 T ),您将获得的0参数版本make_shared()

If you use only one template argument (i.e. T), you get the 0-argument version of make_shared().

这篇关于暧昧超载访问参数少模板函数与可变参数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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