![](/img/trans.png)
[英]Using a member type of templated class as the type of a class member variable
[英]Derive a templated class' member variable type from a template member type
標題可能看起來有點混亂,所以這里有一個更徹底的解釋:
我有一個模板化的 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>>)
如果數據成員的名稱始終相同,則可以通過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>
};
我會在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
當變量名稱不同時,這也是 go 的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.