我可以告诉我的类继承自哪个模板实例类吗? [英] Can I tell which template instance class(es) my class is inheriting from?

查看:156
本文介绍了我可以告诉我的类继承自哪个模板实例类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定此代码:

template < int I >
class Foo
{
public:
    int v;
    Foo() { v = I; }
    virtual ~Foo() {}
};

class Bar : public Foo<0>, public Foo<3>
{
public:
    template < int I >
    int getValue() { return Foo<I>::v; }
};

int main() {
    Bar b;
    cout << b.getValue<0>() << endl; // prints 0
    cout << b.getValue<3>() << endl; // prints 3
    cout << b.getValue<4>() << endl; // compiler error
    return 0;
}

可以遍历所有 Foo< i> ; Bar 继承的类?我们可以假设 i 在0和某些最大值 N 之间。在伪码中:

Is it possible to iterate over all Foo<i> classes from which Bar inherits? We can assume that i is between 0 and some maximum N. In pseudocode:

for ( int i = 0; i < N; i++ )
{
    if ( Bar inherits from `Foo<i>` )
    {
        cout << Foo<i>::v << endl;
    }
}


推荐答案

you go( live example ):

struct _do { template <typename... A> _do(A&&...) { } };

template <int... I>
class Bar_impl : public Foo<I>...
{
public:
    template < int K >
    int getValue() { return Foo<K>::v; }

    template <typename F>
    void loop(F&& f) { _do{(std::forward<F>(f)(getValue<I>()), 0)...}; }
};

using Bar = Bar_impl<0,3>;

现在 Bar 可变参数 I ... 中的类,并以可变方式导出所有基类 Foo <...>

Now Bar implementation holds all indices of base classes in variadic parameter I... and derives all base classes Foo<I>... in a variadic fashion.

函数循环使用辅助 struct _do 。您可以将任意函数,lambda或函数对象 f 传递给 loop 。然后 f 将在 getValue< I>()上调用所有 ,即在每个基类的成员 v 上。

Function loop iterates over all bases using the auxiliary struct _do. You can pass an arbitrary function, lambda or function object f to loop. Then f will be called on getValue<I>() for all I..., i.e., on member v of every base class.

如下:

void print(int i) { cout << i << " "; }

int main() {
    Bar b;
    b.loop(print); // prints 0 3
    cout << endl;
}

换句话说,您不需要如果对象是某个类的实例。

In other words, you don't need to detect if an object is an instance of some class. You make the object know its own bases by construction.

现在你可能意识到,如果你使 Foo code>在成员类型上的模板(而不是 int ),你很接近开始构建自己的基本元组

Now you may realize that if you make Foo a template on the member type (instead of int), you are quite close to start building your own very basic tuple.

这篇关于我可以告诉我的类继承自哪个模板实例类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆