gpt4 book ai didi

c++ - 为什么 std::tuple 和模板派生类的模板参数推导/替换失败?

转载 作者:太空狗 更新时间:2023-10-29 22:56:59 26 4
gpt4 key购买 nike

在接下来的代码中,当我尝试将引用派生类的 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 << "Hello\n";
}

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> .从类型系统的角度来看,它们是完全不同的野兽,当试图为调用找到一个好的匹配时,函数被丢弃。
看错误,很清楚。

How can I fix it?

您可以使用类似这样的方法让它们被接受并仍然强制它们派生自 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 << "Hello\n";
}

// ...

wandbox 上查看它的启动和运行情况.

关于c++ - 为什么 std::tuple 和模板派生类的模板参数推导/替换失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46188666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com