Non-type variadic function templates in C++11

前端 未结 5 1450
有刺的猬
有刺的猬 2020-12-05 23:48

I saw a blog post which used non-type variadic templates (currently not supported by gcc, only by clang).

template 
stru         


        
5条回答
  •  执念已碎
    2020-12-06 00:23

    You are simply confusing type names and non-type names. What you want simply doesn’t work.

    You can probably use variadic non-type templates in functions, but not as (non-template) arguments:

    template 
    int max()
    {
        int tmp = max();
        return N < tmp ? tmp : N;
    }
    
    std::cout << max<3, 1, 4, 2, 5, 0>() << std::endl;
    

    … although I haven’t tested this and I’m not sure how this should work given that you need to have a partial specialisation as the base case. You could solve this by dispatching to a partially specialised struct:

    template 
    struct max_t {
        static int const value = max_t::value > N ? max_t::value : N;
    };
    
    template 
    struct max_t {
        static int const value = N;
    };
    
    
    template 
    int max()
    {
        return max_t::value;
    }
    

    This will work.

提交回复
热议问题