首页 > 解决方案 > 为什么在函数模板的前向引用上没有选择重载?

问题描述

片段:

#include <iostream>

template<typename T>
struct Printer{};

template<typename T>
void test(T&&)
{
    std::cout << "Primary template called\n";
}

template<typename T>
void test(Printer<T>&&)
{
    std::cout << "Specialized template called\n";
}

int main()
{
    auto t = Printer<int>{};
    test(0);
    test(t);
}

这是演示

Primary template called为什么要打印两次?

如果从第二个模板中删除前向引用,则Printer选择重载。

为什么不选择 with &&

标签: c++overloadingfunction-templatesforward-reference

解决方案


转发参考仅适用于T&&,不C<T>&&适用const T&&

test(0); // Call test(T&&) with T=int
test(t); // Call test(T&&) with T=Printer<int>&

推荐阅读