简体   繁体   中英

C++ Initialising Object In Class With Variable In Template

I'm trying to initialise a dMatrix using the following code.

class BpmSolve
{
private:
    const int numZPts;
    Eigen::Matrix<float, 1, numZPts> dMatrix;

public:
    BpmSolve(numberZPoints);
};

BpmSolve::BpmSolve(int numberZPoints)
    : numZPts(numberZPoints),
{
}

The code errors because numZPts is a variable. If I replace numZPts with, say, an integer there are no issues.

What's the correct way to initialise this class? C++11 options are fine.

Thanks.

Eigen::Matrix is a template, and template arguments must be available at compile time. The value of numZPts is not available at compile time - each time you construct a BpmSolve object it may have different value of this field, and the value is not known at compile time. So you ask for something which is not possible.

The numZPts value isn't defined at compile time. If all instances of that class happen to use constants for that value throughout your code, you could simply turn your class into a template parameterized by it:

template <int numZPts>
class BpmSolve {
private:
    Eigen::Matrix<float, 1, numZPts> dMatrix;
    // [...]

BpmSolve::BpmSolve(){
}

Instances become:

BpmSolve<init> instance;

Instead of

BpmSolve instance(init);

This might trigger further changes if this class has inheriting children.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM