Created
April 20, 2011 16:27
-
-
Save kizzx2/931836 to your computer and use it in GitHub Desktop.
C++ compile time detection of member variable with SFINAE
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 Foo | |
{ | |
int one; | |
}; | |
struct Bar | |
{ | |
char one; | |
}; | |
struct Boo : Foo | |
{ | |
int two; | |
}; | |
struct Baz | |
{ | |
int two; | |
}; | |
template <class T> | |
struct HasOne | |
{ | |
typedef char Yes[1]; | |
typedef char No[2]; | |
template <typename C, C> | |
struct Check; | |
struct FakeBase | |
{ | |
int one; | |
}; | |
struct TestSubject : public FakeBase, public T {}; | |
// This would SFINAE because if C really has `one`, it would be | |
// ambiguous | |
template <typename C> | |
static No & Test(Check<int FakeBase::*, &C::one> *); | |
template <typename> | |
static Yes & Test(...); | |
const static bool value = sizeof(Test<TestSubject>(0)) == sizeof(Yes); | |
}; | |
int main() | |
{ | |
std::cout << HasOne<Foo>::value << std::endl; // 1 | |
std::cout << HasOne<Bar>::value << std::endl; // 1 | |
std::cout << HasOne<Boo>::value << std::endl; // 1 | |
std::cout << HasOne<Baz>::value << std::endl; // 0 | |
return 0; | |
} |
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 Foo { int one; }; | |
struct Bar { char one; }; | |
struct Boo : Foo { int two; }; | |
struct Baz { int two; }; | |
template <class T> | |
struct HasOne | |
{ | |
typedef char Yes[1]; | |
typedef char No[2]; | |
template <typename C, C> | |
struct Check; | |
struct FakeBase { int one; }; | |
struct TestSubject : public FakeBase, public T {}; | |
// This would SFINAE because if C really has `one`, it would be | |
// ambiguous | |
template <typename C> | |
static No & Test(Check<int FakeBase::*, &C::one> *); | |
template <typename> | |
static Yes & Test(...); | |
const static bool value = sizeof(Test<TestSubject>(0)) == sizeof(Yes); | |
}; | |
int main() | |
{ | |
std::cout << HasOne<Foo>::value << std::endl; // 1 | |
std::cout << HasOne<Bar>::value << std::endl; // 1 | |
std::cout << HasOne<Boo>::value << std::endl; // 1 | |
std::cout << HasOne<Baz>::value << std::endl; // 0 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment