Last active
August 4, 2019 12:38
-
-
Save nbenn/6d249448bf0c1f11aa51561811f25a19 to your computer and use it in GitHub Desktop.
Runtime index for choosing type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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