slam_duncan
slam_duncan

Reputation: 3668

Construct custom template in C++ class

I have a custom template which I would like to initialise in my C++ class. I would like to directly set the size of it.

Template class, vector3d.hh

template <typename T>
class vector3d {
public:
vector3d(size_t d1=0, size_t d2=0, size_t d3=0, T const & t=T()) :
    d1(d1), d2(d2), d3(d3), data(d1*d2*d3, t){}

T & operator()(size_t i, size_t j, size_t k) {
    return data[i*d2*d3 + j*d3 + k];
}

T const & operator()(size_t i, size_t j, size_t k) const {
    return data[i*d2*d3 + j*d3 + k];
}

private:
    size_t d1,d2,d3;
    std::vector<T> data;
};

Class in which I wouldl like to initialise my template variable:

#include "vector3d.hh"
class foo{
 public:
  vector3d<int> testvector(1000,2000,3000);
}

But trying to compile this code generates the following error pointing at my initialised vector3d:

error: expected identifier before numeric constant

I know this is not how we are meant to construct such things in classes. What is the proper error free for doing this? Assume I cannot use the new C++11 standard.

Upvotes: 1

Views: 87

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254501

"Assume I cannot use the new C++11 standard" - in which case, you can't initialise non-static members in their declarations. You'll have to do it in the constructor:

vector3d<int> testvector;
foo() : testvector(1000,2000,3000) {}

In modern C++, you can initialise it there, but not using (). In-class initialisation can only use = or {}:

vector3d<int> testvector{1000,2000,3000};

Upvotes: 4

Related Questions