Is this portable or at least safe to use with g++?
#include <iostream>
#include <vector>
struct c {};
std::vector<c*> v;
struct i : c { i () { v.push_back (this); } } a, b, c;
int main () {
std::cout << v.size () << "\n"; // outputs 3 with g++
}
EDIT:
Ok, what I need turned out to be a bit harder: The same code with templates:
#include <iostream>
#include <vector>
template < typename T > struct c {};
template < typename T > struct cv { static std::vector<c<T>*> v; };
template < typename T > std::vector<c<T>*> cv<T>::v;
template < typename T > struct i : c<T> { i () { cv<T>::v.push_back (this); } };
cv<int> dummy; // even this won't initialize cv<int>::v
i<int> a, b, d;
int main () {
std::cout << cv<int>::v.size () << "\n"; // outputs 0 :-(
}
How could I fix this to work as above?
EDIT 2:
Here is an ugly fix with macros (I hope there is a better way to do it):
#include <iostream>
#include <vector>
template < typename T > struct c {};
template < typename T > struct cv;
#define INITCV(X) \
struct v##X { static std::vector<c<X>*> v; }; \
std::vector<c<X>*> v##X::v; \
template <> struct cv<X> { typedef v##X V; }
template < typename T > struct i : c<T> { i () { cv<T>::V::v.push_back (this); } };
INITCV(int);
i<int> a, b, d;
int main () {
std::cout << cv<int>::V::v.size () << "\n"; // outputs 3 again :-)
}
(BTW, should I have posted a new question instead of the edits?)