Skip to content

Instantly share code, notes, and snippets.

@kizzx2
Created April 20, 2011 16:27
Show Gist options
  • Save kizzx2/931836 to your computer and use it in GitHub Desktop.
Save kizzx2/931836 to your computer and use it in GitHub Desktop.
C++ compile time detection of member variable with SFINAE
#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;
}
#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