File: sfinaeHasMember.cpp

package info (click to toggle)
dmrgpp 6.06-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 113,900 kB
  • sloc: cpp: 80,986; perl: 14,772; ansic: 2,923; makefile: 83; sh: 17
file content (48 lines) | stat: -rw-r--r-- 731 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <type_traits>

// SFINAE test
// source:
// https://stackoverflow.com/questions/257288/is-it-possible-to-write-a-template-to-check-for-a-functions-existence
template <typename T>
class has_helloworld
{
	typedef char one;
	struct two {
		char x[2];
	};

	template <typename C>
	static one test(typeof(&C::helloworld));
	template <typename C>
	static two test(...);

public:

	enum { value = sizeof(test<T>(0)) == sizeof(char) };
};

class A
{
public:

	int helloworld() const { return 42; }
};

class B
{
};

template <typename T>
typename std::enable_if<has_helloworld<T>::value, int>::type f(const T& t)
{
	return t.helloworld();
}

int main()
{
	A a;
	std::cout << f(a) << "\n";
	// B b;
	// f(b);
}