exo*_*tex 14 c++ templates type-deduction
标题可能看起来有点混乱,所以这里有一个更彻底的解释:
我有一个模板类,它有一个向量作为成员变量。模板参数是一个结构(或类),它将具有一个特定的变量。这个向量的类型应该从模板参数(从这个某个变量)派生出来。棘手的部分是它应该从模板参数的成员变量派生。
#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>>)
Run Code Online (Sandbox Code Playgroud)
son*_*yao 17
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>
};
Run Code Online (Sandbox Code Playgroud)
mch*_*mch 14
我会在structs 中定义类型并在s 中使用它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>>)
Run Code Online (Sandbox Code Playgroud)
https://godbolt.org/z/raE9hbnqW
当变量没有相同的名称时,这也是要走的路。
| 归档时间: |
|
| 查看次数: |
561 次 |
| 最近记录: |