I've been writing some code for a project that includes OpenGL, and I've discovered weird behavior with my vec4 struct, of which I could not find an explanation.
Here's the relevant snippet of my code:
#include <iostream>
using namespace std;
template <class T>
struct vec4 {
T data[4];
vec4(T v1 = (T) 0, T v2 = (T) 0, T v3 = (T) 0, T v4 = (T) 1) {
data[0] = v1;
data[1] = v2;
data[2] = v3;
data[3] = v4;
}
void print() {
cout << "[ " << data[0] << ", " << data[1] << ", " << data[2] << ", " << data[3] << " ]" << endl;
}
};
int main() {
vec4<int> test1; //Instantiating like this is fine
test1.print();
vec4<int> test2(); //Instantiating like this leads to errors
test2.print();
vec4<int> test3(0); //Instantiating like this is also fine
test3.print();
// ...
return 0;
}
As you can see, the only difference is using parentheses or not. When I use the parentheses, I get various errors such as:
main.cpp:222:11: error: request for member 'print' in 'test2', which is of non-class type 'vec4<int>()'
main.cpp:226:18: error: no match for 'operator*' (operand types are 'matrix<int>' and 'vec4<int>()')
I get none of these errors if I exclude the parentheses. (I should note that there is an operator overload function defined, but excluded from my snippet. It works with matrix<int>
and vec4<int>
.)
Does anyone have an explanation to this behavior? Are there any situations where such behavior could lead to problems?
Thank you!