How to create a "defnine" with undetermined arguments?

Asked

Viewed 56 times

2

I’ve seen somewhere for some time that this was possible, and now I need to implement this to make it easier to read the code.

Is the following :

void A::adicionarTodos () {
    lista.adicionar(A1::id);
    lista.adicionar(A2::id);
    [etc...]
    lista.adicionar(An::id);
}

Some class I have for dozens of lines, gets really confused, my goal is to make a simple define like this :

implementar(A,A1,A2, [ETC...],An);

These arguments are all class names

1 answer

4


With "define" I think we can not do, but with "variadic templates" is possible, Although it is something complicated.

#include <iostream>
using namespace std;

void adicionar(int i)
{
   cout << "* adicionando " << i << '\n';
}

void adicionarTodos()
{
}

template <typename A1, typename ... As >
void adicionarTodos(A1 a1, As... as)
{
   adicionar(a1);
   adicionarTodos(as...);
}

int main()
{
   adicionarTodos(1);
   adicionarTodos(2, 3);
   adicionarTodos(4, 5, 6);
}                        

Upshot:

* adicionando 1
* adicionando 2
* adicionando 3
* adicionando 4
* adicionando 5
* adicionando 6

Added later: I think the above solution doesn’t actually answer the question asked. I searched a little further, and based on this answer here of Soen created another solution,:

#include <iostream>
using namespace std;

struct X1 { enum {  i = 1 }; };
struct X2 { enum {  i = 2 }; };
struct X3 { enum {  i = 3 }; };
struct X4 { enum {  i = 4 }; };
struct X5 { enum {  i = 5 }; };
struct X6 { enum {  i = 6 }; };

// condicao de parada do template
template <int i=0> void adicionarTodos() { }

template <typename A1, typename ... As>
void adicionarTodos()
{
   cout << "* adicionando " << A1::i << '\n';
   adicionarTodos<As...>();
}

int main()
{
   adicionarTodos<X1>();
   adicionarTodos<X2,X3>();
   adicionarTodos<X4,X5,X6>();
}
  • Dude, this is like a cheat ! really good this ! It will lose 1 by 1 and in the end makes the template-less method

  • it’s not cheating, that’s how you really use it...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.