【问题标题】:Derive a templated class' member variable type from a template member type从模板成员类型派生模板类的成员变量类型
【发布时间】:2021-07-25 17:41:34
【问题描述】:

标题可能看起来有点混乱,所以这里有一个更详尽的解释:

我有一个模板类,它有一个向量作为成员变量。模板参数是一个结构(或类),它有一个特定的变量。这个向量的类型应该从模板参数(从这个特定的变量)派生。棘手的部分是它应该从模板参数的成员变量派生。

#include <vector>
#include <complex>
using namespace std;

struct thingA {
    double variable;
    //...
};

struct thingB {
    complex<double> variable;
    //...
};


template <class S>
class someClass {
    vector< " type of S::variable " > history; // If S=thingA, make it a double, if S=tingB make it a complex<double>
}

// Usage:
someClass<thingA> myInstanceA; // (this instance should now have a vector<double>)

someClass<thingB> myInstanceB; // (this instance should now have a vector<complex<double>>)

【问题讨论】:

    标签: c++ templates type-deduction


    【解决方案1】:

    如果数据成员的名称始终相同,则可以通过decltype获取类型:

    template <class S>
    class someClass {
        vector< decltype(S::variable) > history; // if S=thingA, make it a double, if S=tingB make it a complex<double>
    };
    

    【讨论】:

      【解决方案2】:

      我会在structs 中定义类型并在class 中使用它:

      #include <vector>
      #include <complex>
      using namespace std;
      
      struct thingA {
          using Type = double;
          Type variable;
          //...
      };
      
      struct thingB {
          using Type = complex<double>;
          Type varbiable;
          //...
      };
      
      
      template <class S>
      class someClass {
          vector<typename S::Type> history; // if S=thingA, make it a double, if S=tingB make it a complex<double>
      };
      
      // usage:
      someClass<thingA> myInstanceA; // (this instance should now have a vector<double>)
      
      someClass<thingB> myInstanceB; // (this instance should now have a vector<complex<double>>)
      

      https://godbolt.org/z/raE9hbnqW

      这也是当变量不具有相同名称时要走的路。

      【讨论】:

      • 这很有帮助!谢谢你。这实际上是我在我的程序中要走的路。虽然宋元尧的回答更适合我原来的(更一般的)问题。非常感谢。我非常喜欢stackoverflow!
      猜你喜欢
      • 2017-11-27
      • 2012-05-25
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多