Created
February 5, 2020 15:55
-
-
Save ram-nad/1b9eca2a078b35998833c8d7b07e04b3 to your computer and use it in GitHub Desktop.
Code for Dev.to C++ Templates and 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> | |
#include <type_traits> | |
template <class T> | |
class check_new_interface { | |
template <class R> | |
static auto check(int) -> decltype(std::declval<R>().getValue(0, 0)); | |
template <class> | |
static double check(double); | |
public: | |
static constexpr bool value = sizeof(decltype(check<T>(0))) == sizeof(int); | |
}; | |
class SupportedBackend { | |
public: | |
int getValue(int data1, int data2) { return data1 + data2; } | |
}; | |
class UnsupportedBackend { | |
public: | |
int getValue(int data) { return data + 1; } | |
}; | |
// template <typename Backend> | |
// class Container { | |
// private: | |
// Backend b; | |
// int data; | |
// int data1, data2; | |
// public: | |
// Container(int data, int data1, int data2) | |
// : data(data), data1(data1), data2(data2) {} | |
// int get() { return b.getValue(data); } | |
// }; | |
template <typename Backend> | |
class Container { | |
private: | |
Backend b; | |
int data; | |
int data1, data2; | |
inline int get(std::false_type) { return b.getValue(data); } | |
inline int get(std::true_type) { return b.getValue(data1, data2); } | |
public: | |
Container(int data, int data1, int data2) | |
: data(data), data1(data1), data2(data2) {} | |
int get() { | |
return get( | |
std::integral_constant<bool, check_new_interface<Backend>::value>()); | |
} | |
}; | |
int main() { | |
Container<UnsupportedBackend> A(1, 2, 3); | |
Container<SupportedBackend> B(1, 2, 3); | |
std::cout << A.get() << std::endl; | |
std::cout << B.get() << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment