C++ introspection on identifying existence of method signatures - c++

I'd like to modernise a common technique I use or perhaps over use. It statically checks for method signatures and calls the methods if they exist. My approach predates C++17 by some time FWIW.
Currently, I used Boost's Type traits like BOOST_TTI_HAS_MEMBER_FUNCTION(event)
which allows something such as
template <typename M, typename E>
static inline typename std::enable_if<
has_member_function_event<current_t, void, boost::mpl::vector<M &, const E &>>::value
>::type
event(M &mux, S &g, const E &e) {
auto &node = boost::fusion::at<N>(g);
node.event(mux, e);
...
It works just fine but, you know, it's not the prettiest. Is there a way I might avoid the macros and join the rest of you in the modern world :-)?
Regards,
--Matt. (aka dinosaur)

Would simple, direct SFINAE suit your needs?
Here's a test function exercising various member functions, checking for adequate return types and const-correctness as well:
template <typename Obj> void exercise(Obj&& obj) {
if constexpr(has_bar(obj)) {
std::cout << "called T bar() -> something or void\n";
obj.bar();
}
if constexpr(converts<int>(has_foo(obj))) {
std::cout << "called int foo() const -> " << obj.foo() << "\n";
}
if constexpr(converts<long>(has_foo(obj, "some text"))) {
std::cout << "called long foo(std::string) -> " << obj.foo("some text") << "\n";
}
}
The has_bar implementation is simply:
template <typename T>
static constexpr auto has_bar(T&& obj) -> exists<decltype(obj.bar())> { return {}; }
template <typename... T>
static constexpr auto has_bar(T&&...) -> does_not_exist { return {}; }
To generically allow for checking signatures and avoid repetitious code, here's a helper macro (obviously optional):
#define DEF_HAS_MEMBER(name) \
template <typename T, typename... Args> \
static constexpr auto has_##name(T&& obj, Args&&... args) \
-> exists<decltype(std::forward<T>(obj).name(std::forward<Args>(args)...))> { return {}; } \
template <typename... T> \
static constexpr auto has_##name(T&&...) -> does_not_exist { return {}; }
DEF_HAS_MEMBER(foo)
DEF_HAS_MEMBER(bar)
The converts predicate now is an ultra-simple addition:
template <typename T, typename R>
static constexpr auto converts(R) { return std::is_convertible_v<typename R::return_type, T>; }
Everything together:
Live On Coliru
#include <string>
#include <type_traits>
#include <iostream>
template <typename R> struct exists : std::true_type { using return_type = R; };
struct does_not_exist : std::false_type { using return_type = void; };
#define DEF_HAS_MEMBER(name) \
template <typename T, typename... Args> \
static constexpr auto has_##name(T&& obj, Args&&... args) \
-> exists<decltype(std::forward<T>(obj).name(std::forward<Args>(args)...))> { return {}; } \
template <typename... T> \
static constexpr auto has_##name(T&&...) -> does_not_exist { return {}; }
DEF_HAS_MEMBER(foo)
DEF_HAS_MEMBER(bar)
struct Everything {
int foo(std::string /*unused*/) { return 42; }
int foo() const { return -1; }
void bar() {}
};
struct Some {
int foo() const { return -2; }
};
template <typename T, typename R>
static constexpr auto converts(R) { return std::is_convertible_v<typename R::return_type, T>; }
template <typename Obj> void exercise(Obj&& obj) {
std::cout << "===== " << __PRETTY_FUNCTION__ << "\n";
if constexpr(has_bar(obj)) {
std::cout << "called T bar() -> something or void\n";
obj.bar();
}
if constexpr(converts<int>(has_foo(obj))) {
std::cout << "called int foo() const -> " << obj.foo() << "\n";
}
if constexpr(converts<long>(has_foo(obj, "some text"))) {
std::cout << "called long foo(std::string) -> " << obj.foo("some text") << "\n";
}
}
int main() {
Everything e;
Everything const ce;
Some s;
Some const cs;
exercise(s);
exercise(cs);
exercise(ce);
exercise(e);
}
Prints
===== void exercise(Obj&&) [with Obj = Some&]
called int foo() const -> -2
===== void exercise(Obj&&) [with Obj = const Some&]
called int foo() const -> -2
===== void exercise(Obj&&) [with Obj = const Everything&]
called int foo() const -> -1
===== void exercise(Obj&&) [with Obj = Everything&]
called T bar() -> something or void
called int foo() const -> -1
called long foo(std::string) -> 42

OK. I have taken Alan Birtles advice and had a look at C++20 concepts for the solution.
Perhaps the use of std::addressof is overkill but it makes it almost a one-liner without a macro to define a HasMethodXYZ concept which may then be used for if constexpr or for easy SFINAE via a constraint. For example:
template <typename T>
concept HasMethodEvent = requires(T a, void (T::*m)(const std::string&) const) {
{&a == std::addressof(a)};
{m = &T::event};
};
struct dude_noway {};
struct dude_no {
void event(std::string& f) const {}
};
struct dude_yes {
void event(const std::string& f) const {}
};
template <typename T>
bool perhaps_event() {
if constexpr (HasMethodEvent<T>) {
return true;
} else {
return false;
}
}
template <HasMethodEvent T>
bool perhaps_event_sfinae() {
return true;
}
template <typename T>
bool perhaps_event_sfinae() {
return false;
}
//Catch2 test-case check
TEST_CASE("simple event check", "[check_method]") {
REQUIRE(perhaps_event<dude_yes>());
REQUIRE_FALSE(perhaps_event<dude_no>());
REQUIRE_FALSE(perhaps_event<dude_noway>());
REQUIRE(perhaps_event_sfinae<dude_yes>());
REQUIRE_FALSE(perhaps_event_sfinae<dude_no>());
REQUIRE_FALSE(perhaps_event_sfinae<dude_noway>());
}
which works OK with clang++-10 using libstdc++-10. For the win, I prefer this to the Boost TTI approach as it co-locates the method signature with the method name as part of the concept rather than using the MPL vector later and it feels simpler.
Thanks, --Matt.

Related

Is there a way to partially match a variadic template parameter pack?

I currently have a system to "connect" signals to functions. This signal is a variadic template that has as template parameters the arguments of the functions it can connect to.
In the current implementation, I obviously cannot connect to functions whose arguments aren't exactly the same (or those that can be converted to) as the signal's parameters. Now, as I'm trying to mimic Qt's signal/slot/connect, I'd also like to connect a signal of N parameters to a slot of M<N parameters, which is perfectly well-defined (i.e. ignore the >M parameters of the signal and just pass the first M to the connected function). For an example of the code I have in its most simplistic form, see Coliru.
So the question is two-fold:
How do I make the connect call work for a function void g(int);?
How do I make the emit call work for a function void g(int);?
I'm guessing I'll have to make some "magic" parameter pack reducer for both the slot and its call function, but I can't see how it all should fit together so it's quite hard to actually start trying to code a solution. I'm OK with a C++17-only solution, if at least Clang/GCC and Visual Studio 2015 can compile it.
The code linked above for completeness:
#include <memory>
#include <vector>
template<typename... ArgTypes>
struct slot
{
virtual ~slot() = default;
virtual void call(ArgTypes...) const = 0;
};
template<typename Callable, typename... ArgTypes>
struct callable_slot : slot<ArgTypes...>
{
callable_slot(Callable callable) : callable(callable) {}
void call(ArgTypes... args) const override { callable(args...); }
Callable callable;
};
template<typename... ArgTypes>
struct signal
{
template<typename Callable>
void connect(Callable callable)
{
slots.emplace_back(std::make_unique<callable_slot<Callable, ArgTypes...>>(callable));
}
void emit(ArgTypes... args)
{
for(const auto& slot : slots)
{
slot->call(args...);
}
}
std::vector<std::unique_ptr<slot<ArgTypes...>>> slots;
};
void f(int, char) {}
int main()
{
signal<int, char> s;
s.connect(&f);
s.emit(42, 'c');
}
template<class...> struct voider { using type = void; };
template<class... Ts> using voidify = typename voider<Ts...>::type;
template<class C, class...Args>
using const_lvalue_call_t = decltype(std::declval<const C&>()(std::declval<Args>()...));
template<class T, std::size_t...Is>
auto pick_from_tuple_impl(T &&, std::index_sequence<Is...>)
-> std::tuple<std::tuple_element_t<Is, T>...>;
template<class Tuple, class = std::enable_if_t<(std::tuple_size<Tuple>::value > 0)>>
using drop_last = decltype(pick_from_tuple_impl(std::declval<Tuple>(),
std::make_index_sequence<std::tuple_size<Tuple>::value - 1>()));
template<class C, class ArgsTuple, class = void>
struct try_call
: try_call<C, drop_last<ArgsTuple>> {};
template<class C, class...Args>
struct try_call<C, std::tuple<Args...>, voidify<const_lvalue_call_t<C, Args...>>> {
template<class... Ts>
static void call(const C& c, Args&&... args, Ts&&... /* ignored */) {
c(std::forward<Args>(args)...);
}
};
Then in callable_slot:
void call(ArgTypes... args) const override {
using caller = try_call<Callable, std::tuple<ArgTypes...>>;
caller::call(callable, std::forward<ArgTypes>(args)...);
}
For member pointer support (this requires SFINAE-friendly std::result_of), change const_lvalue_call_t to
template<class C, class...Args>
using const_lvalue_call_t = std::result_of_t<const C&(Args&&...)>;
then change the actual call in try_call::call to
std::ref(c)(std::forward<Args>(args)...);
This is poor man's std::invoke for lvalue callables. If you have C++17, just use std::invoke directly (and use std::void_t instead of voidify, though I like the sound of the latter).
Not sure to understand what do you exactly want but... with std::tuple and std::make_index_sequence ...
First of all you need a type traits that give you the number of arguments of a function (or std::function)
template <typename>
struct numArgs;
template <typename R, typename ... Args>
struct numArgs<R(*)(Args...)>
: std::integral_constant<std::size_t, sizeof...(Args)>
{ };
template <typename R, typename ... Args>
struct numArgs<std::function<R(Args...)>>
: std::integral_constant<std::size_t, sizeof...(Args)>
{ };
Next you have to add a constexpr value in callable_slot to memorize the number of arguments in the Callable function
static constexpr std::size_t numA { numArgs<Callable>::value };
Then you have to modify the call() method to pack the arguments in a std::tuple<ArgTypes...> and call another method passing the tuple and an index sequence from 0 to numA
void call(ArgTypes... args) const override
{ callI(std::make_tuple(args...), std::make_index_sequence<numA>{}); }
Last you have to call, in CallI(), the callable() function with only the first numA elements of the tuple of arguments
template <std::size_t ... Is>
void callI (std::tuple<ArgTypes...> const & t,
std::index_sequence<Is...> const &) const
{ callable(std::get<Is>(t)...); }
The following is a full working example
#include <memory>
#include <vector>
#include <iostream>
#include <functional>
template <typename>
struct numArgs;
template <typename R, typename ... Args>
struct numArgs<R(*)(Args...)>
: std::integral_constant<std::size_t, sizeof...(Args)>
{ };
template <typename R, typename ... Args>
struct numArgs<std::function<R(Args...)>>
: std::integral_constant<std::size_t, sizeof...(Args)>
{ };
template <typename ... ArgTypes>
struct slot
{
virtual ~slot() = default;
virtual void call(ArgTypes...) const = 0;
};
template <typename Callable, typename ... ArgTypes>
struct callable_slot : slot<ArgTypes...>
{
static constexpr std::size_t numA { numArgs<Callable>::value };
callable_slot(Callable callable) : callable(callable)
{ }
template <std::size_t ... Is>
void callI (std::tuple<ArgTypes...> const & t,
std::index_sequence<Is...> const &) const
{ callable(std::get<Is>(t)...); }
void call(ArgTypes... args) const override
{ callI(std::make_tuple(args...), std::make_index_sequence<numA>{}); }
Callable callable;
};
template <typename ... ArgTypes>
struct signal
{
template <typename Callable>
void connect(Callable callable)
{
slots.emplace_back(
std::make_unique<callable_slot<Callable, ArgTypes...>>(callable));
}
void emit(ArgTypes... args)
{ for(const auto& slot : slots) slot->call(args...); }
std::vector<std::unique_ptr<slot<ArgTypes...>>> slots;
};
void f (int i, char c)
{ std::cout << "--- f(" << i << ", " << c << ")" << std::endl; }
void g (int i)
{ std::cout << "--- g(" << i << ")" << std::endl; }
struct foo
{
static void j (int i, char c)
{ std::cout << "--- j(" << i << ", " << c << ")" << std::endl; }
void k (int i)
{ std::cout << "--- k(" << i << ")" << std::endl; }
};
int main ()
{
std::function<void(int, char)> h { [](int i, char c)
{ std::cout << "--- h(" << i << ", " << c << ")" << std::endl; }
};
std::function<void(int)> i { [](int i)
{ std::cout << "--- i(" << i << ")" << std::endl; }
};
using std::placeholders::_1;
foo foo_obj{};
std::function<void(int)> k { std::bind(&foo::k, foo_obj, _1) };
signal<int, char> s;
s.connect(f);
s.connect(g);
s.connect(h);
s.connect(i);
s.connect(foo::j);
s.connect(k);
s.emit(42, 'c');
}
This example need C++14 because use std::make_index_sequence and std::index_sequence.
Substitute both of they and prepare a C++11 compliant solution isn't really difficult.

Compile-time switch for mutable/immutable lambda

I am writing a class member function that will take a lambda with a given type T in the function argument. My question is: is it possible to overload the member function at compile-time based on the mutability of the argument? Below is the example:
// T is a given type for class.
template <typename T>
class Wrapper {
T _t;
// For T&
template <typename F, typename R = std::result_of_t<F(T&)>>
std::enable_if_t<std::is_same<R, void>::value> operator()(F&& f) {
f(_t);
}
// For const T&
template <typename F, typename R = std::result_of_t<F(const T&)>>
std::enable_if_t<std::is_same<R, void>::value> operator()(F&& f) const {
f(_t);
}
};
So, what I want is, if the give lambda is with the following signature, the first operator should be invoked.
[](T&) {
...
};
For constant argument, the second should be invoked.
[](const T&) {
}
If you plan to use non-capturing lambdas only, you can rely on the fact that they decay to pointers to functions.
It follows a minimal, working example:
#include<type_traits>
#include<iostream>
template <typename T>
class Wrapper {
T _t;
public:
auto operator()(void(*f)(T &)) {
std::cout << "T &" << std::endl;
return f(_t);
}
auto operator()(void(*f)(const T &)) const {
std::cout << "const T &" << std::endl;
return f(_t);
}
};
int main() {
Wrapper<int> w;
w([](int &){});
w([](const int &){});
}
Otherwise you can use two overloaded functions as it follows:
#include<type_traits>
#include<iostream>
#include<utility>
template <typename T>
class Wrapper {
T _t;
template<typename F>
auto operator()(int, F &&f)
-> decltype(std::forward<F>(f)(const_cast<const T &>(_t))) const {
std::cout << "const T &" << std::endl;
return std::forward<F>(f)(_t);
}
template<typename F>
auto operator()(char, F &&f) {
std::cout << "T &" << std::endl;
return std::forward<F>(f)(_t);
}
public:
template<typename F>
auto operator()(F &&f) {
return (*this)(0, std::forward<F>(f));
}
};
int main() {
Wrapper<int> w;
w([](int &){});
w([](const int &){});
}

Fallback function using ellipsis: can we force the size of the parameters pack?

Consider the following code:
#include <utility>
#include <iostream>
struct S {
template<typename T, typename... A>
auto f(A&&... args) -> decltype(std::declval<T>().f(std::forward<A>(args)...), void()) {
std::cout << "has f(int)" << std::endl;
}
template<typename>
void f(...) {
std::cout << "has not f(int)" << std::endl;
}
};
struct T { void f(int) { } };
struct U { };
int main() {
S s;
s.f<T>(42); // -> has f(int)
s.f<U>(42); // -> has not f(int)
// oops
s.f<T>(); // -> has not f(int)
}
As shown in the example the third call to f works just fine, even if the number of arguments is wrong, for it's not wrong at all for the fallback function.
Is there a way to force the number of arguments when an ellipsis is involved that way?
I mean, can I check at compile time that the size of the arguments list is exactly 1, no matter if the main function or the fallback is chosen?
Good solutions are also the ones that only involves the first template function and result in hard-errors instead of soft-errors because of the size of the parameter pack.
Of course, it can be solved with several techniques without using variadic arguments. As an example: int/char dispatching on internal template methods; explicitly specify the arguments list; whatever...
The question is not about alternative approaches to do that, I already know them.
It's just to know if I'm missing something basic here or it's not possible and that's all.
If I understand correctly your issue, you may add a layer:
struct S {
private:
template<typename T, typename... A>
auto f_impl(A&&... args)
-> decltype(std::declval<T>().f(std::forward<A>(args)...), void()) {
std::cout << "has f(int)" << std::endl;
}
template<typename>
void f_impl(...) {
std::cout << "has not f(int)" << std::endl;
}
public:
template<typename T, typename A>
auto f(A&& args) { return f_impl<T>(std::forward<A>(arg)); }
};
With traits, you may do
template <typename T, typename ... Ts>
using f_t = decltype(std::declval<T>().f(std::declval<Ts>()...));
template <typename T, typename ... Ts>
using has_f = is_detected<f_t, T, Ts...>;
struct S {
template<typename T, typename... A>
std::enable_if_t<has_f<T, A&&...>::value && sizeof...(A) == 1> f(A&&... args)
{
std::cout << "has f(int)" << std::endl;
}
template<typename T, typename... A>
std::enable_if_t<!has_f<T, A&&...>::value && sizeof...(A) == 1> f(A&&... args) {
std::cout << "has not f(int)" << std::endl;
}
};
Demo
You can use a function (assert) that gets pointer to a function to deduce size of paramemters :
#include <utility>
#include <iostream>
template <typename...Args>
struct size_assert{
template <typename T,typename R,typename... Params>
constexpr static bool assert(R(T::*)(Params...) )
{
static_assert(sizeof...(Args) == sizeof...(Params),"Incorrect size of arguments!");
return true;
}
};
struct S {
template<typename T, typename... A, bool = size_assert<A...>::assert(&T::f)>
auto f(A&&... args) -> decltype(std::declval<T>().f(std::forward<A>(args)...), void())
{
std::cout << "has f(int)" << std::endl;
}
template<typename>
void f(...) {
std::cout << "has not f(int)" << std::endl;
}
};
struct T { void f(int) { } };
struct U { };
int main() {
// std::cout <<fc(&f);
S s;
s.f<T>(42); // -> has f(int)
s.f<U>(42); // -> has not f(int)
// oops
s.f<T>(); // -> has not f(int)
}

Wrapping a templated function call in a lambda

I am trying to write code to do something similar (code written for demonstration purposes) to this:
template <typename F, typename Args...>
inline auto runFunc(F func) -> foo
{
return foo([func](Args... args) -> std::result_of<F>::type
{
// Do something before calling func
func(args...);
// Do something after call func
});
}
So basically I am trying to write a function that returns an object that takes lambda that matches the templated function type. Obviously this code won't work because I do not have Args... defined. How would I solve this in C++11?
template<class F_before, class F, class F_after>
struct decorate_func_t {
F_before f0;
F f1;
F_after f2;
template<class...Args>
typename std::result_of<F(Args...)>::type operator()(Args&&...args)const{
f0();
auto r = f1(std::forward<Args>(args)...);
f2();
return r;
}
};
template<class F_before, class F, class F_after>
decorate_func_t<F_before, F, F_after>
decorate_func( F_before before, F f, F_after after ){
return {std::move(before), std::move(f), std::move(after)};
}
Then:
template <typename F, typename Args...>
inline auto runFunc(F func) -> foo
{
return foo(decorate_func(
[]{/* Do something before calling func */},
func,
[]{/* Do something after call func */ }
};
}
the lack of auto parameters in C++11 lambdas makes this about the best you can do.
In C++14 this is trivial:
template <class F>
auto runFunc(F func)
{
return foo(
[func](auto&&... args) // ->decltype(auto) maybe
{
// Do something before calling func
auto r = func(decltype(args)(args)...);
// Do something after call func
return r;
}
);
}
note that many nominally C++11 compilers actually support auto parameters on lambdas.
You can use a support structure as in the following example:
#include<type_traits>
#include<cassert>
struct foo {
template<typename F>
foo(F f) { assert(42 == f(42)); }
};
template<typename>
struct S;
template<typename R, typename... Args>
struct S<R(*)(Args...)> {
template <typename F>
static auto runFunc(F func) -> foo
{
return foo{[func](Args... args) -> R
{
// Do something before calling func
auto r = func(args...);
// Do something after call func
return r;
}};
}
};
template<typename F>
inline auto runFunc(F func) -> foo
{
return S<F>::runFunc(func);
}
int f(int i) { return i; }
int main() {
runFunc(f);
}
For it's not clear to me what's the context of the problem, I'm not sure I got exactly what you were asking for.
I hope the code above can help you.
Still being unsure it this is what you're searching for, I risk posting:
#include <iostream>
struct foo
{
template<typename T>
foo(T lambda)
{
lambda(1, 2);
}
};
template <typename F, typename... Args>
inline typename std::result_of<F>::type runFunc(F func)
{
return foo(
[func](Args... args)
{
std::cout << "Before";
func(args...);
std::cout << "After";
}
);
}
struct print
{
void operator()(int i) const
{
std::cout << i << std::endl;
}
void operator()(int i, int j) const
{
std::cout << i << " " << j << std::endl;
}
};
int main()
{
runFunc<print, int, int>(print());
}

boost::typeindex::type_id<T>().pretty_name() is not "pretty"

I am trying to have the type of some variable printed on stdout. This code:
std::string mystr {"dsadsadas"};
std::cout << boost::typeindex::type_id< decltype(mystr) >().pretty_name() << std::endl;
results in:
std::__1::basic_string<char, std::__1::char_traits<char>, std::__1:: allocator<char> >
which is definitely not pretty.. why is this happening? any workaround?? (Note I'm compiling with clang++ using c++14 semantics)
I have a library called cpputil (privately maintained on bitbucket) which has lots of useful shortcuts for c++11 or better.
one of the concepts is cpputil::classname_of(x).
The idea is that if a class has a static member data or function called classname, this is used to print the name of the class. If not, you can supply a free function that provides the classname. Failing that, typeid.name() is used as a fallback.
Now your classnames can be as pretty as you like.
Live On Coliru
#include <iostream>
#include <type_traits>
/// static member of any type
namespace cpputil {
namespace detail {
template<class T>
constexpr auto has_static_member_classname(...)
-> std::false_type
{
return {};
}
template<class T>
constexpr auto has_static_member_classname(int)
-> decltype(T::classname, void(), std::true_type())
{
return {};
}
// static member of type function that returns anything but takes no args
template<class T>
constexpr auto has_static_function_classname(...)
-> std::false_type
{ return {}; }
template<class T>
constexpr auto has_static_function_classname(int)
-> decltype(T::classname(), void(), std::true_type())
{ return {}; }
}
// templated free function that takes no args, used as a fallback but may be overriden
template<class T> decltype(auto) classname() { return typeid(T).name(); }
namespace detail {
template<class T>
constexpr auto has_free_function_classname_0(...)
-> std::false_type
{ return {}; }
template<class T>
constexpr auto has_free_function_classname_0(int)
-> decltype(classname<T>(), void(), std::true_type())
{ return {}; }
// free function that takes a const ref
template<class T>
constexpr auto has_free_function_classname_1(...)
-> std::false_type
{ return {}; }
template<class T>
constexpr auto has_free_function_classname_1(int)
-> decltype(classname(std::declval<T>()), void(), std::true_type())
{ return {}; }
template<class T, typename = void>
struct classname_finder;
// highest priority - if there is a free function taking 1 parameter findable by ADL - use this
template<class T>
struct classname_finder<
T,
std::enable_if_t<
decltype(has_free_function_classname_1<T>(0))::value
>
>
{
static constexpr decltype(auto) apply() { return classname(*reinterpret_cast<const T*>(0)); }
static constexpr decltype(auto) apply(const T& t) { return classname(t); }
};
// priority 2 - if there is a static function, use that
template<class T>
struct classname_finder<
T,
std::enable_if_t<
decltype(has_static_function_classname<T>(0))::value &&
!decltype(has_free_function_classname_1<T>(0))::value
>
>
{
static constexpr decltype(auto) apply() { return T::classname(); }
static constexpr decltype(auto) apply(const T&) { return T::classname(); }
};
// priority 3 - if there is a static data member, use that
template<class T>
struct classname_finder<
T,
std::enable_if_t<
decltype(has_static_member_classname<T>(0))::value &&
!decltype(has_static_function_classname<T>(0))::value &&
!decltype(has_free_function_classname_1<T>(0))::value
>
>
{
static constexpr decltype(auto) apply() { return T::classname; }
static constexpr decltype(auto) apply(const T&) { return T::classname; }
};
// finally, use the cpputil::classname_of<X>() template overload
template<class T>
struct classname_finder<
T,
std::enable_if_t<
!decltype(has_static_member_classname<T>(0))::value &&
!decltype(has_static_function_classname<T>(0))::value &&
!decltype(has_free_function_classname_1<T>(0))::value &&
decltype(has_free_function_classname_0<T>(0))::value
>
>
{
static constexpr decltype(auto) apply() { return classname<T>(); }
static constexpr decltype(auto) apply(const T&) { return classname<T>(); }
};
}
template<class T>
auto classname_of(const T& t)
{
return detail::classname_finder<T>::apply(t);
}
template<class T>
auto classname_of()
{
return detail::classname_finder<T>::apply();
}
}
struct class_a
{
static const char* classname() { return "class_a"; }
};
struct class_b
{
constexpr static const char* classname = "class_b";
};
struct class_c
{
};
namespace cpputil {
template<> decltype(auto) classname<class_c>() { return "class_c"; }
}
struct class_d
{
};
decltype(auto) classname(const class_d&) { return "class_d"; }
struct class_e {
static const std::string& classname() { static const std::string _("class_e static function"); return _; }
};
static const char* classname(const class_e&) {
return "class_e free function should take priority";
}
// no classname decoration. should fall back to typeid() solution
struct class_f {
};
using namespace std;
auto main() -> int
{
class_a a;
class_b b;
class_c c;
class_d d;
class_e e;
class_f f;
cout << cpputil::classname_of(a) << endl;
cout << cpputil::classname_of(b) << endl;
cout << cpputil::classname_of(c) << endl;
cout << cpputil::classname_of(d) << endl;
cout << cpputil::classname_of(e) << endl;
cout << cpputil::classname_of(f) << endl;
cout << endl;
cout << cpputil::classname_of<class_a>() << endl;
cout << cpputil::classname_of<class_b>() << endl;
cout << cpputil::classname_of<class_c>() << endl;
cout << cpputil::classname_of<class_d>() << endl;
cout << cpputil::classname_of<class_e>() << endl;
cout << cpputil::classname_of<class_f>() << endl;
return 0;
}
Prints
class_a
class_b
class_c
class_d
class_e free function should take priority
7class_f
class_a
class_b
class_c
class_d
class_e free function should take priority
7class_f