SemperCallide
SemperCallide

Reputation: 2070

Error with template class constructor taking arguments

I've been looking around the internet for a solution to my problem, but haven't found an example question quite like mine (that I recognize).

I'm trying to create a simple constructor for my template class, but there must be something wrong with my syntax or my implementation because I keep getting the same compilation error when I test it out. It seems to have something to do with the way I am passing arguments because if I create an object with no arguments it compiles fine (which seems odd because I have no constructor that does not take arguments).

vecxd.hpp:

#ifndef JF_VecXd
#define JF_VecXd

template <class T>
class VecXd : public VecXd<T>{
    public: 
        VecXd(T a, T b, T c);   

    private:
         T x, y, z; 

};

template <class T> 
VecXd<T>::VecXd(T a, T b, T c){
    x = a; 
    y = b;
    z = c;
}

#endif

test.cpp:

#include "vecxd.hpp"

int main(){
    int a = 3, b = 4, c = 5;
    VecXd<int> tVec(a,b,c);

    return 0;
}

The error:

3 vecxd.hpp invalid use of undefined type `class VecXd'

But it compiles when I create the object with no arguments, like so:

int a = 1, b = 2, c = 3;
VecXd<int> tVec();

//Instead of this: VecXd<int> tVec(a, b, c)

Thank you very much for your time and I appreciate any advice I could get on this matter.

Upvotes: 2

Views: 181

Answers (1)

Daniel Frey
Daniel Frey

Reputation: 56863

This:

template <class T>
class VecXd : public VecXd<T> {

should be

template <class T>
class VecXd {

as this first would mean that the type is derived from itself - which can never work. The error refers to the base class which is incomplete as it is the class you are just declaring yourself.

What seems to work is

VecXd<int> tVec();

just because this is a function declaration. If you want to have a real instance, drop the brackets:

VecXd<int> tVec;

and you will run into an error with your original code.

Upvotes: 5

Related Questions