Drunk Bearzz
Drunk Bearzz

Reputation: 55

Template object as class parameter gives error before compiling

Here is the code:

#include <iostream>
using namespace std;

template<class OwnerType>
class Move {
public:
    Move() {}
    Move(OwnerType &_owner) {
        owner = &_owner;
    }
    void GetPosition() {
        cout << owner->x << endl;
    }
    OwnerType *owner;
};

class Entity {
public:
    int x = 50;
    Move<Entity> *move;
};


int main() {        
    Entity en; 
    en.x = 77;
    en.move = new Move<Entity>(en);   // sign '=' is underlined by VS
    en.move->GetPosition();
    return 0;
}

Error it gives :

a value of type "Move<Entity> *" cannot be assigned to an entity of type "Move<Entity> *"

The program is compiling, working as expected and gives expected values, however error is still here. It's probably something to do with templates and compiling time and stuff but I don't have enough knowledge to know what this error actually represents.

Also don't worry about leaks since this was just me testing, error is what I don't understand.

Thanks in advance.

Upvotes: 3

Views: 90

Answers (2)

user6169399
user6169399

Reputation:

so it is not Error.

it is Intellisense : see:
Error 'a value of type "X *" cannot be assigned to an entity of type "X *"' when using typedef struct

Visual Studio 2015: Intellisense errors but solution compiles


old:

your main needs ():

this works for me:

#include<iostream>
using namespace std;

template<class T> class Move {
public:
    Move() {}
    Move(T &_owner) {
        owner = &_owner;
    }
    void GetPosition() {
        cout << owner->x << endl;
    }
    T *owner;
};

class Entity {
public:
    int x = 50;
    Move<Entity> *move;
};


int main(){
    Entity en;
    en.x = 77;
    en.move = new Move<Entity>(en);   // sign '=' is underlined by VS
    en.move->GetPosition();

    return 0;
}

output:

77

Upvotes: 1

buld0zzr
buld0zzr

Reputation: 962

Intellisense is known for displaying invalid errors (see for example Visual Studio 2015: Intellisense errors but solution compiles), trust the compiler and linker, as suggested in comments.

However, this error is quite annoying, try closing the solution, delete the .suo file (it's hidden), and open in again. More info on what a .suo file is given here Solution User Options (.Suo) File

Side note, in your code example main is missing ().

Upvotes: 1

Related Questions