Skip to content

Instantly share code, notes, and snippets.

@pperehozhih
Created February 26, 2016 11:00
Show Gist options
  • Save pperehozhih/aa8f693c6e78611f8804 to your computer and use it in GitHub Desktop.
Save pperehozhih/aa8f693c6e78611f8804 to your computer and use it in GitHub Desktop.
replace static_cast to dynamic_cast
#include <iostream>
#include <vector>
#include <cstdlib>
struct test {
};
struct test_virt : public test {
virtual void foo(){}
};
struct test_a : public test_virt {
virtual void foo(){}
};
struct test_b : public test_virt {
virtual void foo(){}
};
struct test_virt_virt : public virtual test_b, public virtual test_a {
virtual void foo(){
}
};
template<typename Res, typename Obj, bool is_class>
struct security_cast_impl {
static Res security_cast(Obj o){
return (Res)o;
}
};
template<typename Res, typename Obj>
struct security_cast_impl<Res, Obj, true> {
static Res security_cast(Obj* o){
return dynamic_cast<Res>(o);
}
};
template<typename Res, typename Obj>
Res security_cast(Obj o){
return security_cast_impl<Res, Obj, std::is_class<Obj>::value>::security_cast(o);
}
#define static_cast security_cast
int main(){
float test_float = 10;
double test_double = static_cast<double>(test_float);
std::cout << test_double <<std::endl;
test_virt* t = new test_b();
std::cout << (void*)static_cast<test_b*>(t) << std::endl;
std::cout << (void*)static_cast<test_a*>(t) << std::endl;
void* ttt = &test_double;
std::cout << (void*)static_cast<test_a*>(ttt) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment