Created
June 22, 2018 14:25
-
-
Save bl4ckb0ne/dd70a2d454b57aaa9251834d316939d9 to your computer and use it in GitHub Desktop.
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 <string> | |
#include <iostream> | |
#include <array> | |
class Foo | |
{ | |
public: | |
Foo() : i(42), d(44.0) {} | |
template<typename T> | |
T get(); | |
template<typename T, size_t n> | |
std::array<T, n> get(); | |
private: | |
template<typename T, size_t n> | |
std::array<T, n> get_impl(); | |
int i = 0; | |
double d = 0.0; | |
}; | |
template<typename T> | |
T Foo::get() | |
{ | |
if constexpr (std::is_same<int, typename std::remove_cv<T>::type>::value) | |
{ | |
return i; | |
} | |
else if constexpr (std::is_same<double, typename std::remove_cv<T>::type>::value) | |
{ | |
return d; | |
} | |
else | |
{ | |
static_assert(sizeof(T) == -1); | |
return T(); | |
} | |
} | |
template<typename T, size_t n> | |
std::array<T, n> Foo::get() | |
{ | |
if constexpr (std::is_same<int, typename std::remove_cv<T>::type>::value) | |
{ | |
std::array<int, n> arr; | |
arr.fill(i); | |
return arr; | |
} | |
else if constexpr (std::is_same<double, typename std::remove_cv<T>::type>::value) | |
{ | |
std::array<double, n> arr; | |
arr.fill(d); | |
return arr; | |
} | |
else | |
{ | |
static_assert(sizeof(T) == -1); | |
return std::array<T, n>(); | |
} | |
} | |
int main() { | |
Foo foo; | |
std::array<int, 4> i = foo.get<int, 4>(); | |
double f = foo.get<double>(); | |
//char c = foo.get<char>(); | |
//float f = foo.get<12, float>(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment