使用模板模板类参数作为参数 [英] Use template template class argument as parameter

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

问题描述

现代C ++设计提供以下示例:

Modern C++ Design gives the following example:

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为参数,在我看来,一些疯狂的递归将要发生。这是怎么可能的?

I couldn't figure how ThreadingModel template would be constructed in a fashion that It could accept SmartPtr as parameter, in my mind some crazy recursion is going to happen. How can this be possible?

编辑

我试过Potatoswatter (sorry lol)comment:

I've tried Potatoswatter (sorry lol) comment:

template <class SmartPtr> struct SingleThreadingModel
{
  class Lock
  {
    public: 
      Lock(SmartPtr&)
      {
      }
  };
};

但它没有工作。

这里是gcc给我的错误:

here is the error that gcc is giving me:

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’


推荐答案

您尝试将 SmartPtr 作为类型参数传递到 ThreadingModel 的SmartPtr 不过是一个模板,而不是一个具体的类型,的注入的类名是不是在继承列表中。

You are trying to pass SmartPtr as a template type argument to ThreadingModel. SmartPtr however is a template, not a concrete type, and the injected class-name is not available in the inheritance list.

另外请注意,你不能只使用默认参数在任意位置(§14.1/ 11 的)模板参数:

Also note that you can't just use default arguments for template parameters in arbitrary positions (§14.1/11):

如果一个模板参数有一个默认的模板参数,其随后所有的模板参数应提供一个默认的模板参数。

If a template-parameter has a default template-argument, all subsequent template-parameters shall have a default template-argument supplied.

修正这些问题的代码:

template
<
  class T,
  template <class> class ThreadingModel,
  template <class> class CheckingPolicy = EnsureNotNull
>
class SmartPtr
  : public CheckingPolicy<T>
  , public ThreadingModel<SmartPtr<T, ThreadingModel, CheckingPolicy> > 
//                         ^ .... now passing a concrete class .... ^
{
    T* operator->() {
        // the following use of SmartPtr is fine as it is the injected class-name:
        typename ThreadingModel<SmartPtr>::Lock guard(*this);
        // ...
    }
};

请注意,现代C ++设计是一本出色的书, t替换一本关于 Vandevoorde / Josuttis 等模板的好书。

Note that while Modern C++ Design is an excellent book, it can't replace a good basic book on templates like Vandevoorde/Josuttis.

这篇关于使用模板模板类参数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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