C++ Variadic Function Templates of Known Type

前端 未结 4 1789
死守一世寂寞
死守一世寂寞 2021-01-04 09:43

I\'m currently trying to get my head around some of the things I can do with variadic template support. Let\'s say I have a function like this -

template <         


        
4条回答
  •  时光说笑
    2021-01-04 10:06

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

    #include 
    #include 
    
    void foo( std::initializer_list l )
    {
        for ( auto el : l )
            // do something
    }
    
    void foo( std::initializer_list l )
    {
    }
    
    void foo( std::initializer_list 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 
    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.

提交回复
热议问题