为什么使用std ::元组和模板派生的类扣除/替换会扣除/替换

Why does template argument deduction/substitution fail with std::tuple and template derived classes?

本文关键字:替换 派生 std 元组 为什么      更新时间:2023-10-16

在下一个代码中,当我尝试将参考派生类的 std::tuple作为参数传递给接收参考基础类std::tuple的函数时,模板参数扣除失败。为什么不能推导编译器模板参数T1T2?我该如何修复?

// Example program
#include <iostream>
#include <tuple>
template<typename T>
struct Base {};
template<typename T>
struct Derived1 : Base<T> {};
template<typename T>
struct Derived2 : Base<T> {};
template<typename T1, typename T2>
void function(std::tuple<Base<T1>&,Base<T2>&> arg)
{
    std::cout << "Hellon";
}
int main()
{
    Derived1<int> d1;
    Derived2<double> d2;
    //function(std::tie(d1, d2));  /* In this case the template argument deduction/substitution failed */
    function<int,double>(std::tie(d1, d2)); /* here works */
    Base<int>& b1 = d1;
    Base<double>& b2 = d2;
    function(std::tie(b1, b2)); /* but, in this case also works */
}

这是行代码function(std::tie(d1, d2));的编译错误:

 In function 'int main()':
25:30: error: no matching function for call to 'function(std::tuple<Derived1<int>&, Derived2<double>&>)' 
25:30: note: candidate is: 
15:6: note: template<class T1, class T2> void function(std::tuple<Base<T>&, Base<T2>&>) 
15:6: note: template argument deduction/substitution failed: 
25:30: note: mismatched types 'Base<T>' and 'Derived1<int>' 
25:30: note: 'std::tuple<Derived1<int>&, Derived2<double>&>' is not derived from 'std::tuple<Base<T>&, Base<T2>&>' 

扣除以这种方式行不通。它可以在任何转换或其他任何东西之前吸入。在这里,编译器期望Base<T>从中推断出T,并且您正在尝试通过DerivedN<T>。从类型系统的角度来看,它们是完全不同的野兽,并且在试图找到呼叫的良好匹配时丢弃了功能。
看看错误,很明显。

我该如何修复?

您可以使用类似的东西让它们接受,但仍然强迫它们源自Base

#include<type_traits>
// ...
template<template<typename> class C1, template<typename> class C2, typename T1, typename T2>
std::enable_if_t<(std::is_base_of<Base<T1>, C1<T1>>::value and std::is_base_of<Base<T2>, C2<T2>>::value)>
function(std::tuple<C1<T1>&, C2<T2>&> arg)
{
    std::cout << "Hellon";
}
// ...

在Wandbox上启动并运行。