这个可变模板示例有什么问题? [英] What is wrong with this variadic templates example?
问题描述
基类是:
#include <memory>
namespace cb{
template< typename R, typename ... Args >
class CallbackBase
{
public:
typedef std::shared_ptr< CallbackBase< R, Args... > >
CallbackPtr;
virtual ~CallbackBase()
{
}
virtual R Call( Args ... args) = 0;
};
} // namespace cb
派生类是这样:
namespace cb{
template< typename R, typename ... Args >
class FunctionCallback : public CallbackBase< R, Args... >
{
public:
typedef R (*funccb)(Args...);
FunctionCallback( funccb cb_ ) :
CallbackBase< R, Args... >(),
cb( cb_ )
{
}
virtual ~FunctionCallback()
{
}
virtual R Call(Args... args)
{
return cb( args... );
}
private:
funccb cb;
};
} // namespace cb
创建函数:
namespace cb{
template < typename R, typename ...Args >
typename CallbackBase< R, Args... >::CallbackBasePtr
MakeCallback( typename FunctionCallback< R, Args... >::funccb cb )
{
typename CallbackBase< R, Args... >::CallbackBasePtr
p( new FunctionCallback< R, Args... >( cb )
);
return p;
}
} // namespace cb
>
And the example :
bool Foo_1args( const int & t)
{
return true;
}
int main()
{
auto cbObj = cb::MakeCallback( & Foo_1args );
}
我一直收到此错误:
error: no matching function for call to ‘MakeCallback(bool (*)(const int&))’
error: unable to deduce ‘auto’ from ‘<expression error>’
我试图改变它,但我不知道如何修复。
I tried to change it, but I couldn't figure out how to fix.
那么,有什么问题?
推荐答案
这个问题可能是一个更简单的例子。尝试在此处识别问题:
The problem might make sense with a simpler example. Try identifying the problem here:
template <typename T>
struct id { typedef T type; };
template <typename T>
void foo(typename id<T>::type x);
foo(5); // error
问题是编译器不能推断 T
应该是;它不是直接在任何地方使用。您必须明确提供它:
foo< int>(5)
,或者让它以其他方式推论:
The problem is that the compiler cannot deduce what T
should be; it's not directly used anywhere. You'd have to explicitly provide it: foo<int>(5)
, or let it deduce it in some other way:
template <typename T>
void foo(typename id<T>::type x, T y);
foo(5, 7); // okay, T is int because 7 is int
这是有道理的:其中 T
,提供给 id
,导致 id< T&
匹配?可能有专门化,如果可能的话,整个事情将是昂贵的。
This makes sense: how could the compiler figure out which T
's, supplied to id
, result in id<T>::type
matching? There could be specializations, and the entire thing would be costly anyway, if possible.
同样,可用于推导 R
和 Args
。您应该这样做:
Likewise, there's nothing the compiler has available to deduce R
and Args
. Instead, you should do this:
template < typename R, typename ...Args >
typename CallbackBase< R, Args... >::CallbackBasePtr
MakeCallback( R cb(Args...) )
{
typename CallbackBase< R, Args... >::CallbackBasePtr
p( new FunctionCallback< R, Args... >( cb ));
return p;
}
最后,还有其他小问题需要修复, Xeo概述了。
Finally, you have other minor issues that need fixing, which Xeo has outlined.
这篇关于这个可变模板示例有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!