Skip to content

Instantly share code, notes, and snippets.

@pfirsich
Last active October 1, 2018 01:42
Show Gist options
  • Save pfirsich/72ec22c4407013eccfab3a78f2ac7a23 to your computer and use it in GitHub Desktop.
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.
#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;
}
@pfirsich
Copy link
Author

pfirsich commented Oct 1, 2018

Output is:

1
0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment