Created
September 13, 2018 12:01
-
-
Save ljmccarthy/14bd06d16c6b52cb5a37c4891e2c75d1 to your computer and use it in GitHub Desktop.
Platform-specific templates for C++
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 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