Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For every template type an argument of a set type

Say I have a variadic template class. How do I create a function such that it's arguments are of a set type, for example int, with the number of arguments being equal to the number of template types?

template <typename... Types>
class Test
{
public:
    void Func(???); // I don't know how to declare such a function
}

Test<string, bool, long> myTest; // Three types
myTest.Func(905, 36, 123315); // Three arguments, but always of type int.

In the end, the goal of the function is to return a tuple of the provided ints. For simplicity I showed the function to be void in the example code.

like image 447
Aart Stuurman Avatar asked Oct 13 '16 07:10

Aart Stuurman


2 Answers

template <typename... Types>
class Test
{
    template <typename>
    using int_t = int;

public:    
    void Func(int_t<Types>... ints)
    {
    }
};

DEMO

like image 88
Piotr Skotnicki Avatar answered Sep 18 '22 18:09

Piotr Skotnicki


wandbox example - (works with C++11)


If you do not require SFINAE, you can use static_assert to make sure your conditions are met:

template <typename... Types>
class Test
{
public:
    template <typename... Ts>
    void Func(Ts...)
    {
        static_assert(sizeof...(Ts) == sizeof...(Types), "");
        static_assert(std::conjunction<std::is_same<Ts, int>...>{}, "");
    }
};

(If you need SFINAE, use std::enable_if.)

std::conjunction checks that all the conditions passed to it are true.


With the above example, the following calls are valid/invalid:

myTest.Func(905, 36, 123315); // valid
myTest.Func(905, 36, 123315.f); // invalid
myTest.Func(905, 22); // invalid

As you can see, implicit conversions are not allowed with this solution. You could use std::is_convertible instead of std::is_same if you want them to be allowed.

like image 30
Vittorio Romeo Avatar answered Sep 22 '22 18:09

Vittorio Romeo