Last active
January 27, 2020 07:04
-
-
Save willowell/14eb78808d34f583fb55954794592d75 to your computer and use it in GitHub Desktop.
Playing with C++20 concepts
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
// Try it out on https://godbolt.org/ with Clang with concepts! | |
// GitHub insists on this having a tab size of 8 even though I told it to use 4, even after deleting and reuploading this. :-( | |
// Please excuse the massive indents! | |
#include <iostream> | |
#include <type_traits> | |
namespace MyProject { | |
template <typename T> | |
using Arithmetic = typename std::enable_if<std::is_arithmetic<T>::value, T>::type; | |
template<typename T> | |
concept ArithmeticConcept = std::is_arithmetic<T>::value; | |
template<typename Arithmetic> | |
Arithmetic add(Arithmetic a, Arithmetic b) { | |
return a + b; | |
} | |
template<ArithmeticConcept A> | |
A addCon(A a, A b) { | |
return a + b; | |
} | |
} | |
int main() { | |
using namespace MyProject; | |
auto a = add<int>(3, 4); | |
auto b = add<double>(3.0, 5.0); | |
auto c = add(std::string("blue"), std::string("yellow")); | |
std::cout << "Output: " << a << std::endl; | |
std::cout << "Output: " << b << std::endl; | |
std::cout << "Output: " << c << std::endl; | |
auto d = addCon<int>(3, 4); | |
auto e = addCon<double>(3.0, 5.0); | |
// auto f = addCon<std::string>(std::string("blue"), std::string("yellow")); | |
std::cout << "Output: " << d << std::endl; | |
std::cout << "Output: " << e << std::endl; | |
// std::cout << "Output: " << f << std::endl; | |
auto g = add<int>(2, 2); | |
auto h = add<long>(2, 2); | |
int i = add(2, 2); | |
auto j = add(2, 2); // type is inferred from argument types; default here is int | |
auto k = add(2ll, 2ll); | |
std::cout << "Size of g: " << sizeof(g) << std::endl; | |
std::cout << "Size of h: " << sizeof(h) << std::endl; | |
std::cout << "Size of i: " << sizeof(i) << std::endl; | |
std::cout << "Size of j: " << sizeof(j) << std::endl; | |
std::cout << "Size of k: " << sizeof(k) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment