Slugger Slugger - 5 months ago 35
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> {
State<N>(size_t b);

long int E();
size_t length;

template<unsigned long N>
: 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/ error: ‘template<long unsigned int N> class State’ used without template parameters
long int State::E(){
state/ In function ‘long int E()’:
state/ error: ‘length’ was not declared in this scope
for (size_t i = 1; i != length; ++i)
state/ 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
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
on a
object for instance. So once the object is instantiated I would like to be able to call
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download