Compilation Error on Recursive Variadic Template Function

后端 未结 2 1906
慢半拍i
慢半拍i 2020-12-16 03:05

I\'ve prepared a simple variadic template test in Code::Blocks, but I\'m getting an error:

No matching function for call to \'OutputSizes()\'

2条回答
  •  被撕碎了的回忆
    2020-12-16 03:36

    It's because you didn't provide a base case. You extracted the last data type of the variadic template parameter- then you tried to match an empty variadic parameter to a function taking a type and a variadic parameter. You need to provide a "base case" for when the variadic parameter is empty.

    using namespace std;
    
    template 
    void OutputSizes()
    {
        std::cout << typeid(FirstDatatype).name() << ": " << sizeof(FirstDatatype) << std::endl;
        OutputSizes();
    }
    
    template
    void OutputSizes() // We're called when there's no template arguments
                       // left in the pack
    {
    }
    
    int main()
    {
        OutputSizes();
        return 0;
    }
    

    Edit: The many-zero overloads I have shown here actually only work when you take actual run-time arguments too based on the template types. If you only take template parameters directly, you have use two-one recursion like shown in Howard Hinnant's answer.

提交回复
热议问题