Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Runtime index for choosing type
// compile: clang++ -Wall -std=c++11 functor-type-switch.cpp -o functor-type-switch
#include <vector>
#include <iostream>
#include <stdexcept>
template <template<typename> class Func, typename ...Ar>
auto dispatch_type(size_t type, Ar&&... rg) ->
decltype(Func<int>()(std::forward<Ar>(rg)...)) {
switch(type) {
case 0: return Func<int>()(std::forward<Ar>(rg)...);
case 1: return Func<double>()(std::forward<Ar>(rg)...);
default: throw std::runtime_error("error");
}
}
template <class T>
struct Length {
size_t operator()(size_t len) {
std::vector<T> vec(len, 100);
return vec.size();
}
};
size_t length(size_t type, size_t len) {
return dispatch_type<Length>(type, len);
}
int main () {
std::cout << "length: " << length(0, 4) << "\n";
std::cout << "length: " << length(1, 5) << "\n";
std::cout << "length: " << length(2, 6) << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.