C++11 别名和模板模板

C++11 alias and template template

本文关键字:别名 C++11      更新时间:2023-10-16

>我有以下类

struct Abis
{
  void foo() { // does something }
};
struct A
{
  typedef Abis bis_type; 
  bis_type create() { // instanciates Abis object };
};
template<class Tbis> // typically Tbis would be Abis
struct Bbis
{
  // something
};
template<class T> // typically T would be A
struct B
{
  typedef Bbis<typename T::bis_type> bis_type; 
  bis_type create() { // instanciates Bbis object };
};

现在我想再加一层:

template<class Tbis, template<class> class Ubis> 
struct Cbis : public Ubis<Tbis>
{
   void additional_method() { // does something calling Tbis and Ubis methods}
};

并有一个类 C 实例化一个 Cbis 对象,这样我就可以写这样的东西:

C<A,B> c();
Cbis<Abis,Bbis> cbis = c.create();
cbis.additional_method();

这需要能够引用 typedef bis_types所以我尝试了这个

template<class T, template<class> class U> 
struct C
{
   template<class S>
   using Ubis_type = U<S>::bis_type // PROBLEM!
   typedef Cbis<typename T::bis_type,Ubis_type> bis_type; 
   bis_type create(); 
}

这似乎不起作用,也没有

template<class T, template<class> class U> 
struct C
{
   template<class S>
   using Ubis_type = typename U<S>::bis_type // PROBLEM!
   typedef Cbis<typename T::bis_type,Ubis_type> bis_type; 
   bis_type create(); 
}

作为临时修复,我可以将 B 类型作为模板参数传递给 Cbis,但这并不真正尊重设计,我想了解问题是什么。

我的语法正确吗?(我正在使用XCode 7.3)

谢谢

主要问题在于您的typedef Bbis bis_type行 - Bbis是类模板而不是类。我认为您的意思很可能是typedef Bbis<T> bis_type(鉴于您在该上下文中具有类型T)。之后,您的代码基本上可以正常工作(我必须更正一些拼写错误才能对其进行编译),这是最终版本:

更新:更改了struct C的定义以适应C<A, B>所需的用例)

struct Abis
{
  void foo() { // does something 
  }
};
struct A
{
  typedef Abis bis_type; 
  bis_type create() { // instanciates Abis object 
    return Abis();
  }
};
template<class Tbis> // typically Tbis would be Abis
struct Bbis
{
  // something
};
template<class T> // typically T would be A
struct B
{
  typedef Bbis<T> bis_type; 
  bis_type create() { // instanciates Bbis object 
  };
};
template<class Tbis, template<class> class Ubis> 
struct Cbis : public Ubis<Tbis>
{
   void additional_method() { // does something calling Tbis and Ubis methods
   }
};
template<class T, template<class> class U> 
struct C
{
   template<class S>
   using Ubis_type = typename U<S>::bis_type; // PROBLEM!
   typedef Cbis<typename U<T>::bis_type,Ubis_type> bis_type; 
   bis_type create()
   {
        return bis_type();    
   } 
};

然后,您可以像这样使用最终struct C

int main(int argc, char**args) 
{
    C<A, B> c;
    auto d = c.create();
    d.additional_method();
    return 0;
}