Skip to content

Instantly share code, notes, and snippets.

@lw
Last active September 22, 2020 20:36
Show Gist options
  • Save lw/d897ac9fcb982a418f78ae1eb5559e22 to your computer and use it in GitHub Desktop.
Save lw/d897ac9fcb982a418f78ae1eb5559e22 to your computer and use it in GitHub Desktop.
Smart switch over TBuffer w/ C++-20 templated lambdas
#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