How to iterate over a boost::fusion sequence? - c++

I'm trying to initialise a list of args to use with fusion::invoke.
The args are all of the form:
template <typename Type>
struct ArgWrapper
{
inline ArgWrapper(){}
inline void Setup(lua_State*L,int idx)
{
//setup this value from the lua state...
//in reality this class is specialised for different lua types
}
operator Type(){return value;}
Type value;
};
So I can do, for example
int add(int a,int b){return a+b;}
fusion::vector<ArgsWrapper<int>,ArgsWrapper<int> > v;
fusion::at_c<0>(v).value=1;
fusion::at_c<1>(v).value=2;
std::cout<<fusion::invoke(add,v)//prints 3
But if I have a fusion sequence of type FusionListType, where I know each type in the sequence is an ArgWrapper of some type, how can I iterate through that list and call the Setup function on each element (I have just one lua_State pointer and want to use it as the first argument for Setup, and I want to use the position in the sequence as the second argument).
So for a vector of size 3 I want the resultant logic to be:
lua_State*L;
fusion::at_c<0>.Setup(L,1);
fusion::at_c<1>.Setup(L,2);
fusion::at_c<2>.Setup(L,3);
I have tried:
template<typename ArgWrapperType,int N>
void FillArgWrapper(ArgWrapperType arg,lua_State*L)
{
fusion::at_c<N>(arg).Setup(L,N+1);
}
template<typename ArgWrapperType>
void FillArgWrapper<ArgWrapperType,0>(ArgWrapperType arg,lua_State*L)
{
fusion::at_c<0>(arg).Setup(L,1);
}
But this fails to compile, saying function template partial specialisation ‘FillArgWrapper<ArgWrapperType, 0>’ is not allowed.
Thanks in advance.

Ok, I figured it out. I need to be using a struct:
template <typename ArgWrapperList,u32 N=mpl::size<ArgWrapperList>::value-1>
struct ArgWrapperListFiller
{
static inline void Setup(ArgWrapperList &args,lua_State*L)
{
fusion::at_c<N>(args).Setup(L,N+1);
ArgWrapperListFiller<ArgWrapperList,N-1>::Setup(args,L);
}
};
template <typename ArgWrapperList> //base case, do not recurse
struct ArgWrapperListFiller<ArgWrapperList,0>
{
static inline void Fill(ArgWrapperList &args,lua_State*L)
{
fusion::at_c<0>(args).Setup(L,1);
};
};

Related

How to define a new function from an existed template function in C++

Recently I am learning the template function in C++. I am wondering if there is any simple way for me to do the following thing.
For example, I have defined a template function in C++ as follow:
template <typename T, float t_p>
void func_a(T* input, T* output):
{
output = input / t_p;
}
Now, I want to define another template function based on this template function for f_p = 4.0. I know I may be able to do the following thing:
template <typename T>
void func_b(T* input, T* output):
{
func_a<T,4.0>(input, output);
}
but this code looks very heavy. Especially when I have many input variables. I am wondering if there is any way that I can do to be similar as follows
template <typename, T>
func_b = func_a<T , 4.0>;
If so, it will be very helpful
You can't do it with functions, but you can do it with functors. S.M. noted that you can't use float as a template non-type parameter, so let's replace it with int. I also suppose that you want to operate on values, not on pointers (either dereference pointers, or use references).
template<int t_p>
struct func_a
{
template<typename T>
void operator()(const T& input, T& output) const
{
output = input / t_p;
}
};
using func_b = func_a<4>;
using func_c = func_a<5>;
Now you can use these functors in the following way:
void foo()
{
int a = 100;
int b;
func_a<2>()(a, b);
func_b()(a, b);
func_c()(a, b);
}
Note that you need extra empty parentheses to create a functor.
If you want to use float you can do something like this:
struct func_a
{
func_a(float p) : p(p) { }
template<typename T>
void operator()(const T& input, T& output) const
{
output = input / p;
}
private:
const float p;
};
void foo()
{
const auto func_b = func_a(4);
const auto func_c = func_a(5);
float a = 100;
float b;
func_a(2)(a, b);
func_b(a, b);
func_c(a, b);
}
Maybe a little Off Topic but I give you a useful, I hope, little suggestion: switch the order of your template parameters.
I mean: write func_a() as follows (I use int for t_p because, as pointed by S.M., a float value can't a valid template parameter)
template <int t_p, typename T>
void func_a(T* input, T* output):
{ output = input / t_p; }
The point is that T can be deduced from the function arguments (input and output) where t_p can't be deduced so must be explicated.
If the order is T first and t_p second, you must explicate also T, so (by example) in func_b() you must write
func_a<T,4>(input, output);
If the order is t_p first and T second, you must explicate only t_p and you can let the compiler deduce the T type; so you can simply write
func_a<4>(input, output);
In this case is a little improvement but, in other circumstances, can be useful.

How to specialize a class-member for multiple template values (constants)?

I'd like to specialize a member-method of a template-class. This template-class has a constant template-parameter of type int and depending on the value different global variables have to be selected:
template <int INSTANCE>
class mailbox
{
public:
void write(uint32_t v);
}
// global accessors of different instances
extern mailbox<0> mailbox0;
extern mailbox<1> mailbox1;
and later in a .cpp-file
template<>
void mailbox<0>::write(uint32_t v)
{
access(reg_0, v);
}
template<>
void mailbox<1>::write(uint32_t v)
{
access(reg_1, v);
}
mailbox<0> mailbox0;
mailbox<1> mailbox1;
This allows me to use the mailbox as follows:
mailbox0.write(0xdeadcafe);
This compiles and links. I'd like to simplify the method by using the constant INSTANCE:
template<int INSTANCE>
void mailbox<INSTANCE>::write(uint32_t v)
{
if (INSTANCE == 0)
access(reg_0, v);
else
access(reg_1, v);
}
But I'm unable to figure the right syntax to make it work. Is this at all possible while keeping my user-code as is? What are the right words and terms for what I want to do in C++-slang?
Isn't the problem just that you are trying to separate a template into .h and .cpp (which, in reality, is rarely feasible in the current standard)?
template <int INSTANCE>
class mailbox
{
public:
void write(uint32_t v){
if (INSTANCE == 0)
access(reg_0, v);
else
access(reg_1, v);
}
}
should work
Maybe you could go other way around - let global variable be a static member of a class parametrized by the same int mailbox is parametrized by. e.g.:
template <int INSTANCE>
struct reg {
static RegType value;
};
template <int INSTANCE>
RegType reg<INSTANCE>::value;
then access to the reg value would be transparent without any specialization:
template<int INSTANCE>
void mailbox<INSTANCE>::write(uint32_t v) {
access(reg<INSTANCE>::value, v);
}
If c++17 is in a game you can make a reg template global variable and let the code be even simpler:
template <int INSTANCE>
RegType reg;
template<int INSTANCE>
void mailbox<INSTANCE>::write(uint32_t v) {
access(reg<INSTANCE>, v);
}
Edit:
If you can't modify the access pattern you could create array of reference wrappers (c++11):
#include <functional>
std::reference_wrapper<RegType> regs[2] {reg_0, reg_1};
template<int INSTANCE>
void mailbox<INSTANCE>::write(uint32_t v) {
access(regs[INSTANCE].get(), v);
}

Function to get field value from template parameter instead of direct access to allow different names for same information

I'm designing a library for internal use.
A function can be
template<typename It>
void doStuff(It begin, It end)
{
// This is example code. The point is to show that I access the data of the iterator
doStuffInternal(it->a, it->b, it->c);
}
This function is a template because I want to accept all kind of iterators, but I have specific expectations on the type that this iterators produce.
At the moment my code assumes an object is passed with a structure like
struct A
{
int a;
std::string b;
BigObject c;
};
I know the calling code of this function will receive data from an external API, and the data will look something like
struct AlmostA
{
int a_;
std::string _b;
AlmostBigObject cc;
};
Now I can't pass this AlmostA to my function and I need to convert it to A (or something that behaves like A), even if all the information are in AlmostA, just with different names (and slightly different types).
What I'm thinking about doing is to create a function to access the fields
inline int getA(const &A a)
{
return a.a;
}
inline std::string& getB(const &A a)
{
return a.b;
}
and so on for every field I need to access, then rewrite my function to be
template<typename It>
void doStuff(It begin, It end)
{
doStuffInternal(getA(*it), getB(*it), getC(*it));
}
Then the calling code can define
inline int getA(const &AlmostA a)
{
return a.a_;
}
inline std::string& getB(const &AlmostA a)
{
return a._b;
}
and call my function with an iterator of AlmostA without any conversion.
What I hope to achieve with this is that the calling code can define how they provide the information, without being forced to have a structure with those specific fields.
I googled around and couldn't find any example of code doing this.
I'm relatively new to C++, so I'd like if this would work, what are the pitfalls of this approach, why is it not popular or not used (I know something kind of similar is done with std::swap, but that's a particular function) what are alternative solutions to present data with different interface in a unified way in the C++ world?
In what namespace does the getter function need to be implemented in order for the compiler to find them?
Your doStuffInternal(getA(*it), getB(*it), getC(*it)) seems solid to me - I would use a struct template with an explicit specialization for every type that you need to support.
template <typename T>
struct adapter;
template <>
struct adapter<A>
{
template <typename T>
decltype(auto) a(T&& x) { return forward_like<T>(x.a); }
template <typename T>
decltype(auto) b(T&& x) { return forward_like<T>(x.b); }
// ...
};
template <>
struct adapter<AlmostA>
{
template <typename T>
decltype(auto) a(T&& x) { return forward_like<T>(x.a_); }
template <typename T>
decltype(auto) b(T&& x) { return forward_like<T>(x._b); }
// ...
};
Using decltype(auto) as the return type and forward_like allows you to preserve the value category of x's members:
static_assert(std::is_same<decltype(adapter<A>::a(A{})), int&&>{});
A lvalue{};
static_assert(std::is_same<decltype(adapter<A>::a(lvalue)), int&>{});
const A const_lvalue{};
static_assert(std::is_same<decltype(adapter<A>::a(const_lvalue)), const int&>{});
wandbox example (of the value category propagation)
The final code will look something like this:
template<typename It>
void doStuff(It begin, It end)
{
adapter<std::decay_t<decltype(*it)>> adp;
doStuffInternal(adp.a(*it), adp.b(*it), adp.c(*it));
}
In C++11, you need to explicitly specify the return type using a trailing return type. Example:
template <typename T>
auto a(T&& x) -> decltype(forward_like<T>(x.a_))
{
return forward_like<T>(x.a_);
}

Function array initialization at compile time with metaprograming

In video-games is common that resources are loaded in a step fashion way, so within a single thread a loading bar can update at each loading step. By example:
1 -> Load texture A
2 -> Update Loading Bar to 2%
3 -> Load texture B
4 -> Update Loading Bar to 4%
5 ...
This can be done in many ways. One of these is define a function for each loading step.
void LoadTextureA()
{
//Loading routine
...
}
This has the advantage of readability, not need too much nested code and even possible in some cases to share loading routines between two game states.
Now what I was thinking was to generalize this "function-for-step" model with templates. Lets say.
template <int S>
struct Foo{
void LoadingStep()
{
}
};
template <>
struct Foo<0>
{
void LoadingStep()
{
//First loading step
...
}
};
Please correct me if I'm wrong. But it appears possible that I can compile-time iterate through 0 .. to N steps using metaprogramming and assign this specialized functions to an array or vector of function pointers.
N steps are known at compile time along with it respective functions.
Function pointer vector would be iterated like this:
template <int Steps>
class Loader {
public:
bool Load()
{
functionArray[m_step]();
if (++m_step == Steps)
return false; //End loading
else
return true;
}
private:
int m_step;
}
Is this possible? I know that that are easier ways to do it. But besides project requirments it's an interesting programming challenge
I achieved it based on Kal answer of a similar problem
Create N-element constexpr array in C++11
template <int S>
struct Foo{
static void LoadingStep()
{
}
};
template <>
struct Foo<0>
{
static void LoadingStep()
{
//First loading step
}
};
template<template<int S> class T,int N, int... Rest>
struct Array_impl {
static constexpr auto& value = Array_impl<T,N - 1, N, Rest...>::value;
};
template<template<int S> class T,int... Rest>
struct Array_impl<T,0, Rest...> {
static constexpr std::array<void*,sizeof...(Rest)+1> value = {reinterpret_cast<void*>(T<0>::LoadingStep),reinterpret_cast<void*>(T<Rest>::LoadingStep)...};
};
template<template<int S> class T,int... Rest>
constexpr std::array<void*,sizeof...(Rest)+1> Array_impl<T,0, Rest...>::value;
template<template<int S> class T,int N>
struct F_Array {
static_assert(N >= 0, "N must be at least 0");
static constexpr auto& value = Array_impl<T,N>::value;
F_Array() = delete;
F_Array(const F_Array&) = delete;
F_Array(F_Array&&) = delete;
};
Using example:
int main()
{
auto& value = F_Array< Foo ,4>::value;
std::cout << value[0] << std::endl;
}
This yields of void* array of pointers to template functions:
Foo<0>::LoadinStep()
Foo<1>::LoadinStep()
Foo<2>::LoadinStep()
Foo<3>::LoadinStep()
Foo<4>::LoadinStep()
Since Foo<1..3> are not specialized they will fall to Default LoadingStep function
Yes. It's possible. And if you use the template metaprogramming, you don't need to use a run time loop, but a recursive call to a template method:
#include <iostream>
// The template numerated methods
template <int S> struct Foo{static void LoadingStep(){}};
template <> struct Foo<0> {static void LoadingStep(){std::cout<<0;}};
template <> struct Foo<1> {static void LoadingStep(){std::cout<<1;}};
template <> struct Foo<2> {static void LoadingStep(){std::cout<<2;}};
// The loader template method
template <int Step>
void Loader()
{
Foo<Step>::LoadingStep();
Loader<Step-1>();
}
// Stopping rule
template <> void Loader<-1>(){}
int main()
{
Loader<2>();
}
If you want an array:
LoadingFunction functionArray[] = {Function0, Function1, Function2};
.....
for (int i = 0; i < nSteps; ++i)
RunStep(i, nSteps, Function[i]);
Or initialize an std container with it.
If you want templates, you could write
for (int i = 0; i < nSteps; ++i)
RunStep(i, nSteps, Function<i>);
except i in Function<i> must be a constant. So you have to do it with a templated recursive something:
template <int i, int NSteps> struct RunSteps
{
void Run()
{
RunStep(i, NSteps, Function<i>);
RunSteps<i+1, NSteps>::Run();
}
};
template <int NSteps> struct RunSteps<NSteps, NSteps>
{
void Run() {}
};
RunSteps<0, NSteps>::Run();
Compile-time iteration doesn't really exist. The for loop and the templated recursive something do exactly the same thing. The compiler is as capable of unrolling a loop, as of inlining a call.
It looks like there's very little to be gained from templatizing this stuff, and lots to lose.
It is not clear why you would want to put templated functions to an array at compile time, but here you go:
LoadingFunction functionArray[] = {Function<0>, Function<1>, Function<2>};
Now if you don't want to enumerate functions manually like that, it could be a bit of a challenge. It doesn't seem possible with either legacy C arrays or any of the std containers. Assuming you really need it, it's possible to write a custom container capable of such initialization.
template <template <int> class FunctionWrappper, int NFunctions>
class MyOptimizedFunctionArray {
// filling this space is left as an exercise
};

Is there a way to make a template match all pointer types?

Is there a way to make a templated C++ function implicitly convert all pointers to a void*? I'm working on a lightweight Lua binding and I'd like to avoid writing the exact same function for every pointer type when the void* version is all I need.
Declaration:
template<class T>
T GetFromStack(lua_State* L, int index);
Definition:
template<> void* GetFromStack<void*>(lua_State* L, int index)
{
return lua_touserdata(L, index);
}
If I was to call myVariable = GetFromStack<MyStruct*>(L, 0);, the C++ compiler would complain that I haven't defined a function for a MyStruct*. Is it possible to have every pointer type matched to the void* version implicitly?
EDIT:
I see how my question is a bit confusing, I'm not really sure how to word it. I'm attempting to come up with an automatic binding system. This GetFromStack function is called from another templated function:
template<class T_return, class T_param1, class T_param2 >
int LuaFunction(lua_State* L, T_return (*func)(T_param1,T_param2));
which is implemented like this:
template<class T_return, class T_param1, class T_param2 >
int LuaFunction(lua_State* L, T_return (*func)(T_param1,T_param2))
{
T_param1 a = GetFromStack<T_param1>(L, 1);
T_param2 b = GetFromStack<T_param2>(L, 2);
T_return ret = func(a,b);
PushLuaType(L, ret); // <-- This is another templated function
// like GetFromStack that has the same problem
return 1;
}
I then create a Lua version of whatever function I want to expose to Lua with a simple macro:
#define DeclareLuaFunction(function) \
static int ##function##_lua_(lua_State* L) \
{ \
return LuaFunction(L, function); \
}
This works really well so long as I use the predefined types. I have versions of GetFromStack written for all the "basic" types (int, float, etc) and obviously void*. But I don't want to have to write one for every one of my custom type's pointers. When I create a function that uses a MyStruct2, I'd have to write yet another version of GetFromStack that's identical to every other pointer version.
This system would be used like this:
struct MyStruct
{
int a;
float b;
};
int AddToMyStruct(MyStruct* s, int x)
{
int original = s->a;
s->a += x;
return original;
}
DeclareLuaFunction(AddToMyStruct);
Which would then have T_return as an int, T_param1 as a MyStruct* and T_param2 as an integer too. I already have int versions of GetFromStack and PushLuaType, but I don't have MyStruct* versions. With the way it's implemented now, I'd have to write a new version of GetFromStack for every type I come up with, even though every implementation would be the same.
EDIT: Andreas' solution would work if theres a way I can determine if a type is a pointer or not at compile type. If my T_param1 is a MyStruct*, it will be passed as such to GetFromStack, instead of as a MyStruct.
If I understand it correctly, you need to implement the function differently for different types, but the implementation happens to be the same for all pointer types.
If the value was passed as a parameter, you'd use normal function overloading. In this case, you can use enable_if.
template<typename T>
typename std::enable_if<std::is_pointer<T>::value, T>::type
GetFromStack(lua_State* L, int index)
{
return lua_touserdata(L, index);
}
Ok, here's a new try based on your additional info. As has been said before, much of this could be done much easier if you opt to use C++11, but this should work in most older compilers as well.
First you need a way to detect whether your template param T is a pointer, you could either use std::is_pointer<> (which is preferable) or define one yourself like:
template <class T>
struct is_pointer
{
enum {value = false};
};
template <class T>
struct is_pointer<T *>
{
enum {value = true};
};
template <class T>
struct is_pointer<const T *>
{
enum {value = true};
};
Next you need to alter your implementation based on it. To do that we introduce a helper class (or struct as I'm too lazy to write public) which has several specializations, one for each ordinary type and one for pointers:
template <bool ispointer, class T>
struct GetFromStackHelper;
template <>
struct GetFromStackHelper<false, int>
{
static int GetFromStackFun(lua_State *l, int index)
{
return lua_tointeger(l, index);
}
};
// ... add the rest of the built in types here
template <class T>
struct GetFromStackHelper<true, T>
{
static T GetFromStackFun(lua_State *l, int index)
{
return static_cast<T>(lua_touserdata(l, index));
}
};
Finally we tie it together with the GetFromStack function, which now should not have any specializations:
template <class T>
T GetFromStack(lua_State *l, int index)
{
return GetFromStackHelper<is_pointer<T>::value, T>::GetFromStackFun(l, index);
}
Which you could use as:
int i = GetFromStack<int>(luaState, 6);
MyStruct *p = GetFromStack<MyStruct *>(luaState, 5);
I'm not quite sure if this is what you're looking for, but...
How about passing function pointers?
Your compiler's probably going to give you a bunch of warnings, but it should work.
void *GetFromStack(void *p, int index, void * (*func)(void *, int)) {
return func(p, index);
}
void * (*func)(void *, int) is a function pointer to one that takes a void pointer and an int and returns a void pointer, which you supply as the first 2 parameters to GetFromStack. Just use the reference operator & to get a function pointer for the function you want it to call.