的Modern C++ Design给了下面的例子:使用模板模板类参数作为参数
template <class T> struct EnsureNotNull
{
static void Check(T*& ptr)
{
if (!ptr) ptr = GetDefaultValue();
}
};
template
<
class T,
template <class> class CheckingPolicy = EnsureNotNull,
template <class> class ThreadingModel
>
class SmartPtr
: public CheckingPolicy<T>
, public ThreadingModel<SmartPtr>
{
...
T* operator->()
{
typename ThreadingModel<SmartPtr>::Lock guard(*this);
CheckingPolicy<T>::Check(pointee_);
return pointee_;
}
private:
T* pointee_;
};
我想不出怎样的ThreadingModel模板会以一种方式构成,即它可以接受的SmartPtr为参数,在我心中一些疯狂的递归将会发生。这怎么可能?
编辑:
我试过Potatoswatter(不好意思笑)评论:
template <class SmartPtr> struct SingleThreadingModel
{
class Lock
{
public:
Lock(SmartPtr&)
{
}
};
};
但它did'nt工作。
这里是GCC是给我的错误:
main.cpp:28:35: error: type/value mismatch at argument 1 in template parameter list for ‘template<class> class ThreadingModel’
main.cpp:28:35: error: expected a type, got ‘SmartPtr’
啊,是的。模板模板参数。有史以来最令人困惑的事情之一。 – 2010-08-12 21:59:52
你的新代码看起来很好。你得到什么错误,在哪里?另外,一个Tomatoswatter听起来会让它变得一团糟,我试图避免这样做。 – Potatoswatter 2010-08-13 01:09:04