由派生类设置的constexpr基类成员

时间:2017-11-13 20:42:45

标签: c++ constexpr

我想做这样的事情:

// a base class for a family of devices
class foobar_base()
{
    int _n;

public:

    foo_base(int num_of_things) : _n(num_of_things){}

    // I would like to use this from derived classes, where
    // constants are required, such as array sizes...
    constexpr int num_of_things() const {return _n;}


};

// a specific device that has 5 things
class foo: public foobar_base
{
public:
    // foo has 5 things
    foo():foo_base(5){}
};

// a specific device that has 10 things
class bar: public foobar_base
{
public:
    // bar has 10 things
    bar():foo_base(10){}
};


// some class or code that wants to use the family of devices
// represented by the base class...
class foobar_user()
{
    shared_ptr<foobar_base> f(new foo())

    // I want this to have the number of things that foo has
    int array_for_foo_things[f->num_of_things()];

    shared_ptr<foobar_base> b(new bar())

    // and this to have the number of things that bar has
    int array_for_bar_things[b->num_of_things()];

};

我要做的是使用来自派生类的信息通过基类指针,其中需要常量,如下所示:

    int array_for_foo_things[f->num_of_things()];

显然,我可以使用向量而不是数组作为解决方法,但是希望找到一种方法从基类的派生类设置的基类指针中获取constexpr。

1 个答案:

答案 0 :(得分:0)

遵循user0042的想法,你的意思是这样的吗?

#include <iostream>
#include <memory>

// a base class for a family of devices
template<int _N>
class foobar_base
{
    // int _n;

public:

    foobar_base() {}

    // I would like to use this from derived classes, where
    // constants are required, such as array sizes...
    constexpr int num_of_things() const {return _N;}
};

// a specific device that has 5 things
class foo: public foobar_base<5>
{
public:
    // foo has 5 things
    foo() {}
};

// a specific device that has 10 things
class bar: public foobar_base<10>
{
public:
    // bar has 10 things
    bar(){}
};


// some class or code that wants to use the family of devices
// represented by the base class...
int main()
{
    std::shared_ptr<foobar_base<5>> f(new foo());

    // I want this to have the number of things that foo has
    int array_for_foo_things[f->num_of_things()];

    std::shared_ptr<foobar_base<10>> b(new bar());

    // and this to have the number of things that bar has
    int array_for_bar_things[b->num_of_things()];

    std::cout<<"foo: "<<sizeof(array_for_foo_things)/sizeof(int)<<std::endl;
    std::cout<<"bar: "<<sizeof(array_for_bar_things)/sizeof(int)<<std::endl;
}