Can variadic expansions be used as a chain of comma-operator calls?

前端 未结 1 1222
后悔当初
后悔当初 2021-01-03 04:36

I was looking at \"How to properly use references with variadic templates,\" and wondered how far comma expansion can go.

Here\'s a variant of the answer:

         


        
相关标签:
1条回答
  • 2021-01-03 05:12

    Unpacking is only allowed in certain contexts, and comma separated statements doesn't belong to them. Using your words: The expansion is semantically and not lexically. However, it doesn't matter because there are several other ways of doing it. There are already some kind of patterns/idioms to write simple variadic functions. One way of doing it:

    Use a helper template function, that does nothing at all:

    template <typename ...Args>
    void pass(Args&&...) { }
    

    Instead of using the comma operator, pass the expressions to this function:

    template <typename ...Args>
    void inc(Args&&... args)
    {
        pass(++std::forward<Args>(args)...);
    }
    

    You can use the comma operator within the expansion, if the expressions have to be more complex. This might be useful in your case, if some operator++ have return type void:

        pass((++std::forward<Args>(args), 0)...);
    
    0 讨论(0)
提交回复
热议问题