Skip to content
Snippets Groups Projects
Commit e5753f2b authored by Avi Kivity's avatar Avi Kivity Committed by Pekka Enberg
Browse files

Add helper for converting designated initializers to C++


Unfortunately, C++ does not support designated initializers.  Add a function
that helps fill their place.

Use example:

-static struct netisr_handler ether_nh = {
-       .nh_name = "ether",
-       .nh_handler = ether_nh_input,
-       .nh_proto = NETISR_ETHER,
-       .nh_policy = NETISR_POLICY_SOURCE,
-       .nh_dispatch = NETISR_DISPATCH_DIRECT,
-};
+static netisr_handler ether_nh = initialize_with([] (netisr_handler& x) {
+       x.nh_name = "ether";
+       x.nh_handler = ether_nh_input;
+       x.nh_proto = NETISR_ETHER;
+       x.nh_policy = NETISR_POLICY_SOURCE;
+       x.nh_dispatch = NETISR_DISPATCH_DIRECT;
+});

Signed-off-by: default avatarAvi Kivity <avi@cloudius-systems.com>
Signed-off-by: default avatarPekka Enberg <penberg@cloudius-systems.com>
parent a888f210
No related branches found
No related tags found
No related merge requests found
/*
* Copyright (C) 2013 Cloudius Systems, Ltd.
*
* This work is open source software, licensed under the terms of the
* BSD license as described in the LICENSE file in the top-level directory.
*/
#ifndef INITIALIZE_HH_
#define INITIALIZE_HH_
#include <type_traits>
// helper to find out the argument type of a function object
template <typename T>
struct first_argument_type_of;
// special case: free function
template <typename T, typename Ret>
struct first_argument_type_of<Ret (T)> {
typedef T type;
};
// special case: member function pointer
template <typename T1, typename T2, typename Ret>
struct first_argument_type_of<Ret (T1::*)(T2)> {
typedef T2 type;
};
// special case: member function pointer (const)
template <typename T1, typename T2, typename Ret>
struct first_argument_type_of<Ret (T1::*)(T2) const> {
typedef T2 type;
};
// general case: class, look at operator()(T)
template <typename T>
struct first_argument_type_of {
typedef typename first_argument_type_of<decltype(&T::operator())>::type type;
};
template <typename T>
using first_argument_no_ref = typename std::remove_reference<typename first_argument_type_of<T>::type>::type;
/// \file Initialization helper for C designated initializers
/// \fn T initialize(func f)
/// \brief C compatibility for designated initializers
///
/// Unfortunately C++ does not support designated initializers; so
/// this function helps fill its place by default-initializing an object
/// and then calling a user supplied function (usually a lambda) to complete
/// initialization.
template <typename func>
auto initialize_with(func f) -> first_argument_no_ref<func>
{
first_argument_no_ref<func> val = {};
f(val);
return val;
}
#endif /* INITIALIZE_HH_ */
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment