Home > Net >  Cannot extend C template class by additional parameter
Cannot extend C template class by additional parameter

Time:01-24

I'm beginner in C templates and I cannot inherit my derived class from base one with additional parameter. I have base class:

// idproc.h file
#include <array>

using namespace std;
template<class T, int numGroups>
class BaseSequence
{
public:
    int m_numGroups;
    array<T, numGroups> m_groups;
    int m_currPos;

public:
    BaseSequence() : m_numGroups(numGroups), m_currPos(0) {
        std::fill(begin(m_groups), end(m_groups), T());
    }
    virtual string PrintSequence() {
        string identifier;
        for (auto &&group : m_groups)
        {
            identifier  = to_string(group)   "-";
        }
        identifier.pop_back();
        return identifier;
    }
};

My derived class is :

template<class T, int numGroups, int maxVal>
class IdentifierSequence : BaseSequence<T, numGroups> 
{
    int m_maxVal;
public:
    using BaseSequence<T, numGroups>::PrintSequence;
    IdentifierSequence(int maxVal): m_maxVal(maxVal) {}; // compiler error
};

As you can see my IdentifierSequence has additional parameter called m_maxVal, I need to initialize it in constractor.

I'm using it by following way:

// main.cpp file
    
#include <iostream>
#include "idproc.h"

int main(int argc, char** argv) {

    IdentifierSequence<int, 10, 2> is;
    std::cout << is.PrintSequence() << std::endl;

    return 0;
}

Please explain me how to fix this problem.

CodePudding user response:

Your template parameter and constructor accept two variables named maxVal, so you have ambiguity error. You should change the name of either of them.

template<class T, int numGroups, int maxVal_templ> // note: maxVal -> maxVal_templ
class IdentifierSequence : BaseSequence<T, numGroups> 
{
    int m_maxVal;
public:
    using BaseSequence<T, numGroups>::PrintSequence;
    IdentifierSequence(int maxVal): m_maxVal(maxVal) {};
};

CodePudding user response:

Remove the parameter from the constructor, like so:

IdentifierSequence(): m_maxVal(maxVal) {}

Then it will compile.

You can access maxVal directly, no need to pass it to the constructor.

If the value is never changed during execution, you don't even need m_maxVal, depending on your usage. You can use the template parameter anywhere in the class.

  • Related