[英]Carrying type information in class template instantiation
I need to access type information from a class I used to instantiate another class. 我需要从我用来实例化另一个类的类中访问类型信息。
Specifically void Beta<T>::do_something()
needs to accept parameters of type W, S
that were used to instantiate class Alpha<W, S>
. 具体地说
void Beta<T>::do_something()
需要接受类型的参数W, S
了用来实例化类Alpha<W, S>
template<typename W, S>
class Alpha {
public:
using carry_W = W;
using carry_S = S;
};
template<typename T>
class Beta {};
template<typename T>
void Beta<T>::do_something(typename T::carry_W p1, typename T::carry_S p2) {}
Beta<Alpha<int, double>> b;
The solution above works fine but is there any other way to do this without aliasing the types as class members? 上面的解决方案工作正常,但有没有其他方法来做这个没有别名作为类成员的类型? Is there a more "C++" way of doing this?
有没有更“C ++”的方式来做到这一点?
You can create a class template that consists only of a forward declaration and a partial specialisation. 您可以创建仅包含前向声明和部分特化的类模板。
#include <iostream>
using namespace std;
template<typename W, typename S>
class Alpha {
};
template<typename>
class Beta;
template<typename W, typename S, template<typename, typename> class T>
class Beta<T<W,S>> {
public:
void do_something(W w, S s) {
cout << w << ", " << s << '\n';
}
};
int main() {
Beta<Alpha<int, double>> b;
b.do_something(0, 0.0);
}
Do you mean something like the following (template 'pattern matching')? 你的意思是如下(模板'模式匹配')?
template<typename T<W, S>>
void Beta<T>::do_something(W, S) {...}
While I think your question is totally legit, I fear that the current C++ does not allow this shortcut... 虽然我认为你的问题是完全合法的,但我担心当前的C ++不允许这种捷径......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.