Commit 1ffd5e8d authored by Lizan Zhou's avatar Lizan Zhou Committed by htuch
Browse files

fix static initialization fiasco (#116)


and use type_index instead of hash_code for associative containers.

tested locally with latest envoy master.

Signed-off-by: default avatarLizan Zhou <lizan@tetrate.io>
Showing with 7 additions and 9 deletions
+7 -9
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <typeinfo> #include <typeinfo>
#include <typeindex>
#include <unordered_map> #include <unordered_map>
namespace pgv { namespace pgv {
...@@ -20,26 +21,23 @@ using ValidationMsg = std::string; ...@@ -20,26 +21,23 @@ using ValidationMsg = std::string;
class BaseValidator { class BaseValidator {
protected: protected:
static std::unordered_map<size_t, BaseValidator*> validators; static std::unordered_map<std::type_index, BaseValidator*>& validators() {
static auto* validator_map = new std::unordered_map<std::type_index, BaseValidator*>();
return *validator_map;
}
}; };
#if !defined(WIN32)
std::unordered_map<size_t, BaseValidator*> __attribute__((weak)) BaseValidator::validators;
#else
__declspec(selectany) std::unordered_map<size_t, BaseValidator*> BaseValidator::validators;
#endif
template <typename T> template <typename T>
class Validator : public BaseValidator { class Validator : public BaseValidator {
public: public:
Validator(std::function<bool(const T&, ValidationMsg*)> check) : check_(check) Validator(std::function<bool(const T&, ValidationMsg*)> check) : check_(check)
{ {
validators[typeid(T).hash_code()] = this; validators()[std::type_index(typeid(T))] = this;
} }
static bool CheckMessage(const T& m, ValidationMsg* err) static bool CheckMessage(const T& m, ValidationMsg* err)
{ {
auto val = static_cast<Validator<T>*>(validators[typeid(T).hash_code()]); auto val = static_cast<Validator<T>*>(validators()[std::type_index(typeid(T))]);
if (val) { if (val) {
return val->check_(m, err); return val->check_(m, err);
} }
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment