Skip to content

Instantly share code, notes, and snippets.

@ljmccarthy
Created September 13, 2018 12:01
Show Gist options
  • Save ljmccarthy/14bd06d16c6b52cb5a37c4891e2c75d1 to your computer and use it in GitHub Desktop.
Save ljmccarthy/14bd06d16c6b52cb5a37c4891e2c75d1 to your computer and use it in GitHub Desktop.
Platform-specific templates for C++
#include <iostream>
struct Platform {
const char *name;
};
static constexpr Platform Linux{"Linux"};
static constexpr Platform Windows{"Windows"};
template <const Platform *platform>
class PlatformSpecific {
public:
void printPlatformName() {
std::cout << platform->name << std::endl;
}
void doSomething();
};
template <>
void PlatformSpecific<&Linux>::doSomething()
{
std::cout << "call some Linux-specific code" << std::endl;
}
template <>
void PlatformSpecific<&Windows>::doSomething()
{
std::cout << "call some Windows-specific code" << std::endl;
}
#define TargetPlatform (&Linux)
int main()
{
auto ps = PlatformSpecific<TargetPlatform>();
ps.printPlatformName();
ps.doSomething();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment