Last active
September 22, 2020 20:37
-
-
Save lw/6e7779891267a52d9a0c11977f1e9396 to your computer and use it in GitHub Desktop.
Smart switch over TBuffer w/ C++-14 "auto" lambdas
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
#include <iostream> | |
struct CpuBuffer {}; | |
struct CudaBuffer {}; | |
template<typename TBuffer> | |
int getValue(); | |
int cpuValue = 1; | |
int cudaValue = 2; | |
template<> | |
int getValue<CpuBuffer>() { | |
return cpuValue; | |
} | |
template<> | |
int getValue<CudaBuffer>() { | |
return cudaValue; | |
} | |
enum class DeviceType { | |
kCpu, | |
kCuda, | |
}; | |
template <typename TVisitor> | |
auto smartSwitch(DeviceType dt, TVisitor visitor) { | |
switch (dt) { | |
case DeviceType::kCpu: | |
return visitor(CpuBuffer{}); | |
case DeviceType::kCuda: | |
return visitor(CudaBuffer{}); | |
default: | |
throw std::runtime_error(""); | |
} | |
} | |
int main() { | |
std::cout << smartSwitch(DeviceType::kCpu, [](auto buf){ return getValue<decltype(buf)>(); }) << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment