RamblingMad
RamblingMad

Reputation: 5528

Number of arguments specified by template

I have a class that needs to adapt the number of arguments a member std::function takes depending on the classes template parameters. The parameters are declared like so:

template<char Id, char ... Ids>
class term;

Then in the body of the class I have a std::function that needs to take 1 + sizeof...(Ids) arguments of some numeric type (all of the same type).

The body is declared like so:

template<char Id, char ... Ids>
class term{
    public:
        template<typename ... Args>
        void operator()(Args &&... args){
            fn(std::forward<Args>(args)...);
        }

        std::function<void(/* whats do? */)> fn;
};

How can I go about this?

Upvotes: 2

Views: 83

Answers (2)

skypjack
skypjack

Reputation: 50568

A possible approach would be using an alias template, as an example:

template<char...>
using Arg = int; // or whatever is your type

// ...

std::function<void(Arg<>, Arg<Ids>...)> fn;

Or even:

template<char>
using Arg = int; // or whatever is your type

// ...

std::function<void(Arg<Id>, Arg<Ids>...)> fn;

It follows a minimal, working example:

#include<type_traits>
#include<functional>
#include<cassert>

template<char...>
using Arg = int;

template<char Id, char ... Ids>
class Term {
public:
    template<typename ... Args>
    void operator()(Args &&... args){
        fn(std::forward<Args>(args)...);
    }

    std::function<void(Arg<>, Arg<Ids>...)> fn;
};

int main() {
    Term<'a', 'b', 'c'> term;
    assert((std::is_same<decltype(term.fn), std::function<void(int, int, int)>>::value));
}

Upvotes: 0

Qaz
Qaz

Reputation: 61970

Since you haven't stated what the parameter types are for fn, I'll assume all char. In that case:

std::function<void(char, decltype(Ids)...)> fn;

You can adjust this to make the parameters different types, but how you adjust it can depend on what the signature should look like exactly.

For all the same numeric type, the easiest adjustment is probably this:

std::function<void(char, decltype(Ids, YourNumericType{})...)> fn;

Upvotes: 2

Related Questions