从模板成员类型派生模板化 class' 成员变量类型

Derive a templated class' member variable type from a template member type

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

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

#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>>)

我会在 struct 中定义类型并在 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

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

你可以通过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>
};