Skip to content

Instantly share code, notes, and snippets.

@janekolszak
Created November 6, 2014 07:40
Show Gist options
  • Save janekolszak/b9d8fed9aa0833dacc7a to your computer and use it in GitHub Desktop.
Save janekolszak/b9d8fed9aa0833dacc7a to your computer and use it in GitHub Desktop.
Type erasure
#include <iostream>
#include <memory>
#include <functional>
using voidFun = void(*)(std::shared_ptr<void>);
template<typename T>
void fun(std::shared_ptr<T> t)
{
std::cout << *t << std::endl;
}
int main()
{
std::function<void(std::shared_ptr<void>)> call;
call = reinterpret_cast<voidFun>(fun<std::string>);
call(std::make_shared<std::string>("Hi there!"));
call = reinterpret_cast<voidFun>(fun<int>);
call(std::make_shared<int>(33));
call = reinterpret_cast<voidFun>(fun<char>);
call(std::make_shared<int>(33));
// Output:,
// Hi there!
// 33
// !
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment