从基本对象获取派生类的模板参数
简而言之:
- 我有一个没有模板参数的基类
A_base
和一个有两个模板参数的派生类A
。 - 函数
foo()
只接受基类对象 foo()
应该返回一个与派生类的 first 模板参数 T。
这样做的原因是我不想将 foo() 专门用于 A 的所有变体,您可以想象可能有数百个变体。
为了在 代码 中说明这一点:
#include <cstdlib>
struct A_base
{
};
template <typename T, size_t S>
struct A : A_base
{
using P = T; // <-- how do I get here from base class A?
T arr[S];
};
template <typename T>
auto foo(const A_base& ref) -> decltype(/* somehow get P*/)
{
return /* object of type P */;
}
int main()
{
A<int, 10> a;
foo(a);
}
我将另一个参数 P 键入到 T,因为我认为这将使类“拥有”该类型并提供更好的访问。我希望有一个没有虚拟方法的解决方案,因为到目前为止我一直在使用虚拟调用。
In short:
- I have a base class
A_base
without template parameters and a derived classA
that has two. - The function
foo()
only accepts base class objects foo()
is supposed to return an object which has the same type as the derived classes' first template parameter T.
The reason for this is that I don't want to specialize foo() for ALL variations of A which you can imagine could be hundreds.
To illustrate this in code:
#include <cstdlib>
struct A_base
{
};
template <typename T, size_t S>
struct A : A_base
{
using P = T; // <-- how do I get here from base class A?
T arr[S];
};
template <typename T>
auto foo(const A_base& ref) -> decltype(/* somehow get P*/)
{
return /* object of type P */;
}
int main()
{
A<int, 10> a;
foo(a);
}
I typedefd another parameter P to T because I thought this would make the class "own" the type and provide for better access. I was hoping for a solution without virtual methods, because I got around using virtual calls until now.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编译器需要在编译时知道foo()的返回类型。如果您不能使A_Base成为模板,为什么不使FOO()本身成为函数模板?
如:
The compiler needs to know the return type of foo() at compile time. If you cannot make A_base a template, why not make foo() itself a function template?
As in:
很抱歉回答我自己的问题,但我发现了一种可能性。我只是创建一个中间虚拟类
A_middle
,其中只有一个从A
继承的模板参数 T。然后我可以使用这个中间类而不是 foo() 参数的基类:Sorry for answering my own question but I found a possibility. I just create an intermediary dummy class
A_middle
with only one template parameter T that is inherited fromA
. I can then use this intermediary class and not the base class forfoo()
's parameters: