Slugger Slugger - 25 days ago 6
C++ Question

Member function of derived class does not care about template argument

I want to simulate a chain of particles either in the up position or the down position. To this end I made a class that inherits from bitset. It looks like:

#include <bitset>
using namespace std;

template <size_t N>
class State : public bitset<N> {
public:
State<N>();
State<N>(size_t b);

long int E();
private:
size_t length;
};

template<unsigned long N>
State<N>::State()
: std::bitset<N>(), length(N)
{}

template<unsigned long N>
State<N>::State(size_t b)
: std::bitset<N>(b), length(N)
{}


Once such an object is instantiated using a certain length, I would like to find the energy associated to such an object. I want to do this

#include "state.h"

long int State::E(){
long int e = 0;
for (size_t i = 1; i != length; ++i)
e += (test[i] == test[i - 1]) ? 1 : -1;

return e;
}


I receive the error

state/state.cc:3:10: error: ‘template<long unsigned int N> class State’ used without template parameters
long int State::E(){
^~~~~
state/state.cc: In function ‘long int E()’:
state/state.cc:5:27: error: ‘length’ was not declared in this scope
for (size_t i = 1; i != length; ++i)
^~~~~~
state/state.cc:6:11: error: ‘test’ was not declared in this scope
e += (test[i] == test[i - 1]) ? 1 : -1;
^~~~


I understand this to mean that the compiler does not recognize that
E()
is a member function of my class due to a missing template argument. However, I was hoping there is a way that I can call
s.E()
on a
State<20>
object for instance. So once the object is instantiated I would like to be able to call
E()
without having to again specify the size. Is this possible? Thanks in advance!

Answer Source

There are two issues here: defining the member function E() of the class template State<N>, and accessing the test() member function of the dependent base class bitset<N>.

template<size_t N>
long int State<N>::E(){
  long int e = 0;
  for (size_t i = 1; i != length; ++i)
    e += (this->test(i) == this->test(i - 1)) ? 1 : -1;
}

Note both the template<size_t N> and the State<N> as well as the this-> in front of test. See this Q&A for a detailed explanation.

Final note: also be careful: it's test() (parentheses) and operator[] (brackets) in std::bitset.