提问者:小点点

嵌套模板类型的C++类成员变量


我想创建一个模板化的类(C2),使用一个也是模板化的类(C1)作为模板。 此外,在C2中创建一个相同类型的变量,该变量用作类C1的模板。

template <typename Ttype>
class C1{
public:
    Ttype var;
}

template<class T> //class T always templated
class C2{
public:
    T x;
//  ? y; << variable of template type of the class T
}

int main()
{
    C1<int>  instanceInt;
    C1<long> instanceLong;
    
    C2<C1<int>> foo; //C2.y should be int
}

我对C2类的初始实现如下所示,但是它导致错误:标识符“tType”未定义。 为什么编译器看不到tType?

template <template <class Ttype> class Tparam>
class C2 {

public:
    Tparam<Ttype> x;
    const Ttype y;
};

所以我的工作,但不是很好的解决方案是使用typedef。

template <typename Ttype>
class C1{
public:
    typedef Ttype Ctype
    Ttype var;
}

template<class T>
class C2{
public:
    typedef typename T::Ctype Ttype;
    T x;
    Ttype y;
}

我希望同样的功能应该有一个更好的实现。 有吗?


共2个答案

匿名用户

第二种方法是可以固定的,然而,第三种方法也不错。

template <typename Ttype>
class C1
{
public:
    Ttype var;
};

template<template <class Ttype> class Tparam, typename T>
class C2
{
public:
    Tparam<T> x;
    T y;
};

void foo()
{
    C2<C1,int> bar;
}

匿名用户

您可以使用模板专门化

template <typename>
class C2;

template <template <typename> class C, typename T>
class C2<C<T>>
 {
   public: 
      C<T> x;
      T    y;
 };

或者您也可以开发一个自定义类型特征来从类型中提取模板参数

template <typename>
struct get_tmpl_param;

template <template <typename> class C, typename T>
struct get_tmpl_param<C<T>>
 { using type = T; };

template <typename T>
using get_tmpl_param_t = typename get_tmpl_param<T>::type;

因此您的类C2(没有专门化)可以

template <typename T>
class C2
 {
   public:
      T                    x;
      get_tmpl_param_t<T>  y;
 };
  

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(嵌套|模板|类型|c++|类|成员|变量)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?