Last active
September 22, 2020 20:36
-
-
Save lw/d897ac9fcb982a418f78ae1eb5559e22 to your computer and use it in GitHub Desktop.
Smart switch over TBuffer w/ C++-20 templated 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.template operator()<CpuBuffer>(); | |
case DeviceType::kCuda: | |
return visitor.template operator()<CudaBuffer>(); | |
default: | |
throw std::runtime_error(""); | |
} | |
} | |
int main() { | |
std::cout << smartSwitch(DeviceType::kCpu, []<typename TBuffer>(){ return getValue<TBuffer>(); }) << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment