为什么使用std ::元组和模板派生的类扣除/替换会扣除/替换
Why does template argument deduction/substitution fail with std::tuple and template derived classes?
在下一个代码中,当我尝试将参考派生类的 std::tuple
作为参数传递给接收参考基础类std::tuple
的函数时,模板参数扣除失败。为什么不能推导编译器模板参数T1
和T2
?我该如何修复?
// 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上启动并运行。
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 在派生函数中指定void*参数
- 如何通过派生类函数更改基类中的向量
- 如何委托派生类使用其父构造函数?
- 如何用转义符替换字符串中的所有特殊字符
- 如何使用单独文件中的派生类访问友元函数对象
- 派生类销毁的最佳实践是什么
- 如何使用基类指针引用派生类成员
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 存储模板类型以强制转换回派生<T>
- 需要从 istream 和 ostream 派生 iostream
- 在 C++ 中用派生类型重写成员函数
- 具有多个类、派生类的C++正向声明
- 替换派生对象向量中的对象"no matching function to call"
- 为什么使用std ::元组和模板派生的类扣除/替换会扣除/替换
- 如何将基类替换为派生基类