Beowulf99
Beowulf99

Reputation: 25

"Type Name is not allowed" issue

So I'm trying to make a header file for math to implement in my game engine. I declared a struct and a function to simply return the struct.

typedef struct 
{   
    double x, y;

} Vector2D;

static inline Vector2D vector2D (double x, double y) { return (Vector2D) {x, y}; }

I am using Visual Studio 2010 and it it showing an error.

Error: type name is not allowed

What can possibly go wrong? Is there any way to fix it? Thanks in advance.

Upvotes: 1

Views: 958

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117258

What can possibly go wrong?

You are trying cast {x, y} to a Vector2D here:

return (Vector2D) {x, y};

Is there any way to fix it?

Since you are using Visual Studio 2010 I'm assuming that you are using a C++ standard prior to C++11.

Here's how it could be done in C++98 or C++03:

#include <iostream>

struct Vector2D {   // note: typedef is not needed for struct/class in C++
    double x, y;
};

static inline Vector2D vector2D(double x, double y) {
    Vector2D rv = {x, y}; 
    return rv;
}

int main() {
    Vector2D rv = vector2D(10, 20);
    std::cout << rv.x << ' ' << rv.y << '\n';
}

An alternative could be to add a constructor to Vector2D:

#include <iostream>

struct Vector2D {
    Vector2D(double X, double Y) : x(X), y(Y) {}
    double x, y;
};

static inline Vector2D vector2D(double x, double y) {
    return Vector2D(x, y);
}

int main() {
    Vector2D rv = vector2D(10, 20);
    std::cout << rv.x << ' ' << rv.y << '\n';
}

Upvotes: 3

Related Questions