Last active
October 1, 2018 01:42
-
-
Save pfirsich/72ec22c4407013eccfab3a78f2ac7a23 to your computer and use it in GitHub Desktop.
A function `getVar` that gets the value of a static variable inside a class (template argument) and returns a default value, if that static variable is not present.
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> | |
using VarType = int; | |
const VarType DEFAULT_VAR = 0; | |
struct doesHaveVar { | |
static const VarType var = 1; | |
}; | |
struct doesNotHaveVar { | |
}; | |
// "..."" vs "int" lowers this function's priority, so if T::var is present, the other function will be chosen over this | |
template <class T> | |
constexpr VarType getVarImpl(const T* t, ...) { | |
return DEFAULT_VAR; | |
} | |
// T::var is a substitution failure, so if var is not present, this will be ignored | |
template <class T> | |
constexpr typename std::enable_if<!std::is_void<decltype(T::var)>::value, VarType>::type | |
getVarImpl(const T* t, int) { | |
return T::var; | |
} | |
// We need the indirection, so T has to be deduced for getVarImpl | |
template <typename T> | |
constexpr VarType getVar() { | |
return getVarImpl(static_cast<T*>(nullptr), 0); | |
} | |
int main(int argc, char** argv) { | |
std::cout << getVar<doesHaveVar>() << std::endl; | |
std::cout << getVar<doesNotHaveVar>() << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output is: