Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variadic template only using type parameter

Tags:

c++

I would like to do something like this:

#include <iostream>

class a {

public:
    a() : i(2) {}

    template <typename ...ts>
    void exec() {
        f<ts...>();
        std::cout << "a::()" << std::endl;
    }

    int i;
private:

    template <typename t>
    void f() {
        i += t::i;
    }

    template <typename t, typename ...ts>
    void f() {
        f<t>();
        f<t, ts...>();
    }
};

struct b {
    static const int i = -9;
};

struct c {
    static const int i = 4;
};


int main()
{
    a _a;

    _a.exec<b,c>();

    std::cout << _a.i << std::endl;
}

The idea is to get the same information from a group of classes, without the need of an object of each class.

Does anyone know if it is possible?

Thanks!

like image 360
canellas Avatar asked Jun 26 '26 22:06

canellas


2 Answers

In case Your compiler does not support C++17:

template <typename ...ts>
void f() {
    for ( const auto &j : { ts::i... } )
        i += j;
}
like image 61
bartop Avatar answered Jun 29 '26 01:06

bartop


In C++17, your class would simply be

class a {

public:
    a() : i(2) {}

    template <typename ...ts>
    void exec() {
        ((i += ts::i), ...); // Folding expression // C++17
        std::cout << "a::()" << std::endl;
    }

    int i;
};

Possible in C++11 too, but more verbose.

like image 24
Jarod42 Avatar answered Jun 29 '26 01:06

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!