CRTP和模板模板参数限制

svo*_*ron 7 c++ templates crtp template-meta-programming

我正在尝试使用CRTP,但我很困惑为什么以下代码无法编译.

template<template<class...> class CBase>
struct ComponentX : public CBase<ComponentX>
  {
  // This does NOT compile
  };

template<template<class...> class CBase>
struct ComponentY : public CBase<int>
  {
  // This does compile
  };
Run Code Online (Sandbox Code Playgroud)

您知道在CRTP的情况下模板模板参数是否有一些限制?

Sto*_*ica 8

类模板名称仅在打开{类模板定义之后,在其范围内表示"当前特化"(即它是注入的类名).在此之前,它是一个模板名称.

因此CBase<ComponentX>尝试将模板作为参数传递给它CBase,它需要一组类型.

修复很简单:

template<template<class...> class CBase>
struct ComponentX : public CBase<ComponentX<CBase>> // Specify the arguments
  {
  // This should compile now
  }; 
Run Code Online (Sandbox Code Playgroud)

ComponentX<CBase> 是您希望作为类型参数提供的特化的名称.