This problem of mine was reproduced on cpp.sh with C++14 activated (I don't know if that is relevant...)
I have this program:
// Example program 1
#include <iostream>
#include <vector>
class Constants
{
public:
static const int64_t constant_1 = -123;
};
int main()
{
std::vector<int64_t> vec;
vec.push_back(static_cast<int64_t>(Constants::constant_1));
std::cout << vec.size() << std::endl;
}
The output is:
1
Now I try to remove the static_cast
. This gives me this program:
// Example program 2
#include <iostream>
#include <vector>
class Constants
{
public:
static const int64_t constant_1 = -123;
};
int main()
{
std::vector<int64_t> vec;
vec.push_back(Constants::constant_1);
std::cout << vec.size() << std::endl;
}
This gives the following output:
/tmp/cceayEj1.o: In function `main':
:(.text.startup+0x2): undefined reference to `Constants::constant_1'
collect2: error: ld returned 1 exit status
My understanding is that it is ok to initialize static members in the class declaration (How to initialize a static const member in C++?) so I guess this is not related to initialization.
Why do I have to static_cast
in my exampel program?