Skip to content

Instantly share code, notes, and snippets.

@kkourt
Last active December 21, 2016 15:40
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 kkourt/3c1d304e4238acc7a8cf344cb9e78ee0 to your computer and use it in GitHub Desktop.
Save kkourt/3c1d304e4238acc7a8cf344cb9e78ee0 to your computer and use it in GitHub Desktop.
Playing around with C++ concepts.
#include <string>
// Simple C++ concepts example for future reference
// compile with `gcc -Wall -fconcepts -std=c++1z concepts.cc -c -Wall` using a
// recent gcc (I'm using 6.2).
//
// https://accu.org/index.php/journals/2157
// https://accu.org/index.php/journals/2198
// http://en.cppreference.com/w/cpp/language/constraints
// Define a Configuration concept that has a constructor that takes a string
template<typename T>
concept bool Configuration() {
return std::is_constructible<T, std::string>::value;
// Note that the following would not work as expected
//return requires(T a) {
// std::is_constructible<T, std::string>::value;
//};
// Instead, you would need:
// return requires(T a)
// requires std::is_constructible<T, std::string>::value;
//};
}
// Define a Subsystem concept with:
// - a start method
// - a stop method
// - a ::Conf inner type
// - that adheres to the Configuration concept above
template<typename T>
concept bool Subsys() {
return requires(T a) {
{ a.start() } -> int;
{ a.stop() } -> int;
typename T::Conf;
requires Configuration<typename T::Conf>();
};
}
struct SubsysDummy {
struct Conf {
Conf() {}
// XXX: does not match the Configuration concept
Conf(std::string, int) {}
};
SubsysDummy(Conf c) {}
int start(void) { return 0;}
int stop(void) { return 0;}
};
// static assertion will fail, but will not explain the error (gcc 6.2)
//static_assert(Subsys<SubsysDummy>(), "SubsysDummy does not adhere to Subsys");
// This, on the other hand, explains the error
template<typename T> requires Subsys<T>()
constexpr bool SubsysTest() {return true;}
static_assert(SubsysTest<SubsysDummy>(), "SubSysTest does not adhere to SubSys");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment