Skip to content

Instantly share code, notes, and snippets.

@halfelf
Created May 14, 2020 03:05
Show Gist options
  • Save halfelf/5c43d54931179702aedddc401a018f16 to your computer and use it in GitHub Desktop.
Save halfelf/5c43d54931179702aedddc401a018f16 to your computer and use it in GitHub Desktop.
ODR test
cmake_minimum_required(VERSION 3.16)
project(odr_test)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_executable(odr_test main.cpp)
add_library(odrl SHARED lib.cpp)
target_include_directories(odr_test PUBLIC ${PROJECT_SOURCE_DIR})
target_include_directories(odrl PUBLIC ${PROJECT_SOURCE_DIR})
target_link_libraries(odr_test PUBLIC dl)
#include <template.hpp>
bool func() {
auto& fac = Factory<int>::get_instance();
fac.add("100", 100);
fac.show();
return true;
}
bool b = func();
#include <iostream>
#include <template.hpp>
#include <dlfcn.h>
int main() {
void* handle = dlopen("./libodrl.so", RTLD_NOW);
if (handle == nullptr) {
std::cerr << "dlopen failed" << std::endl;
return -1;
}
auto& f = Factory<int>::get_instance();
f.show();
int k = 0;
auto b = f.find("100", k);
std::cout << "k = " << k << " b = " << b << std::endl;
return 0;
}
#ifndef ODR_TEST_TEMPLATE_HPP
#define ODR_TEST_TEMPLATE_HPP
#include <iostream>
#include <map>
#include <string>
template <typename T>
class Factory {
public:
std::map<std::string, T> m;
static Factory<T>& get_instance();
Factory<T>() = default;
Factory<T>(const Factory<T>&) = delete;
Factory<T>(Factory<T>&&) = delete;
void operator=(const Factory<T>&) = delete;
void operator=(Factory<T>&&) = delete;
void add(const std::string& s, const T& t) {
m.emplace(s, t);
}
bool find(const std::string& s, T& t) {
auto iter = m.find(s);
if (iter != m.end()) {
t = iter->second;
return true;
}
return false;
}
void show() {
for (const auto& kv : m) {
std::cout << kv.first << ' ' << kv.second << std::endl;
}
}
};
template <>
Factory<int>& Factory<int>::get_instance(){
static Factory<int> fac;
return fac;
};
#endif//ODR_TEST_TEMPLATE_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment