C++ 模板包推导——我在这个例子中做错了什么?

C++ template pack deduction - What am I doing wrong in this example?

编译并运行良好:

template<typename T, typename ... Args>
void func()
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
    func<Args...>();
}

int main()
{
    func<int, char, float>();
    return 0;
}

...这也可以编译并正常工作:

struct Object {};   // Some dummy object

template<typename T, typename ... Args>
void func(Object *a)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
    func<Args...>(a);
}

int main()
{
    Object *a = new Object;
    func<int, char, float>(a);
    return 0;
}

...但这不会编译,因为它无法解析 T:

struct Object {};   // Some dummy object

template<typename T, typename ... Args>
void func(Object *a, Object *b)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
    func<Args...>(a, b);
}

int main()
{
    Object *a = new Object;
    Object *b = new Object;
    func<int, char, float>(a, b);
    return 0;
}

我在这里做错了什么?抱歉没能穿上Ideone,工作被屏蔽了

正如@NathanOliver 所指出的,您的代码既不编译也不使用 clang nor using gcc

实例化了以下函数:

func<int, char, float>()
func<char, float>()
func<float>()

现在,参数包为空,编译器尝试实例化func<>,导致无法推导模板参数T的错误。

为了正确结束递归,您可以使用this SO question的答案之一,例如:

#include <iostream>

template <typename Last>
void func()
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

template<typename First, typename Second, typename ... Args>
void func()
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
    func<Second, Args...>();
}

int main()
{
    func<int, char, float>();
    return 0;
}

live example

输出

void func() [First = int, Second = char, Args = <float>]
void func() [First = char, Second = float, Args = <>]
void func() [Last = float]