C++ Variadic Function Templates of Known Type

北城余情 提交于 2019-12-04 02:51:36

This should work:

void foo(int);

template<typename ...Args>
void foo(int first, Args... more)
{
   foo(first);
   foo(std::forward(more)...);
}
Pierre Fourgeaud

If you know the types before, you can use function overload with std:initializer_list :

#include <initializer_list>
#include <iostream>

void foo( std::initializer_list<int> l )
{
    for ( auto el : l )
        // do something
}

void foo( std::initializer_list<float> l )
{
}

void foo( std::initializer_list<std::string> l )
{
}

int main()
{
    foo( {1, 2, 3, 4 } );
    foo( {1.1f, 2.1f, 3.1f, 4.1f } );
    foo( { "foo", "bar", "foo", "foo" } );
    return 0;
}

If you use Visual Studio 2012, you might need the Visual C++ Compiler November 2012 CTP.

EDIT : If you still want to use variadic template, you can do :

template <int ... Args>
void foo( )
{
    int len = sizeof...(Args);
    int vals[] = {Args...};
    // ...
}

// And

foo<1, 2, 3, 4>();

But you have to remember that it is not working with float and std::string for example : you will end with 'float': illegal type for non-type template parameter. float is not legal as a non-type template parameter, this is to do with precision, floating point numbers cannot be precisely represented, and the likelyhood of you referring to the same type can depend on how the number is represented.

podkova

I'm currently trying to get my head around some of the things I can do with variadic template support.

Assuming that you want to experiment with variadic templates, not find any solution to your problem, then I suggest taking a look at the code below:

#include <iostream>

template<int ...Values>
void foo2()
{
    int len = sizeof...(Values);
    int vals[] = {Values...};

    for (int i = 0; i < len; ++i)
    {
        std::cout << vals[i] << std::endl;
    }
}

int main()
{
    foo2<1, 2, 3, 4>();

    return 0;
}

The difference between foo2 and your foo is that you pass the parameters to foo at runtime, and to foo2 at compilation time, so for every parameter set you use, compiler will generate separate foo2 function body.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!