问题描述
是的,标题可以吓唬婴儿,但它实际上是很直接。
Yeah, the title can scare babies, but it's actually quite straightforward.
我试图存储一个功能指针专门的模板函数,即boost :: make_shared(boost 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 )
错误,供参考:
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 = ]
如果我注释掉非可变变量,代码编译得很好。
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..n 个参数。
这应该工作:
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
),你得到 make_shared()
的0参数版本。
If you use only one template argument (i.e. T
), you get the 0-argument version of make_shared()
.
这篇关于不确定的重载访问无参数模板函数与可变参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!