Skip to content

Instantly share code, notes, and snippets.

@skyzh
Created October 15, 2019 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skyzh/f4cb78b920a0e4adce33fcf0a6bbde16 to your computer and use it in GitHub Desktop.
Save skyzh/f4cb78b920a0e4adce33fcf0a6bbde16 to your computer and use it in GitHub Desktop.
Templated parameter with default value will throw compile error.
#include <iostream>
#include <functional>
using namespace std;
template <typename T>
bool compare_by_value(const T& a, const T& b) { return a < b; }
template <typename Comp>
bool alex_compare_int(const int& a, const int &b, Comp comp = compare_by_value) {
return comp(a, b);
}
template <typename Value, typename Comp = bool(&)(const Value&, const Value&)>
bool alex_compare(const Value& a, const Value& b, Comp comp = compare_by_value) {
return comp(a, b);
}
int main() {
// fail
cout << alex_compare_int(1, 2) << endl;
// ok
cout << alex_compare(1, 2) << endl;
cout << alex_compare(1, 2, function(compare_by_value<int>)) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment