在变差函数的不同参数包中推导两个不同的已知类型变量
deduce two different known type variables in different parameter packs within a variadic function
我有以下代码:
template <typename... Type1, typename... Type2>
void foo(const Type1&&... t1, Type2&&... t2)
{
int len = sizeof...(Type1);
cout << len << endl;
int len1 = sizeof...(Type2);
cout << len1 << endl;
}
int main()
{
foo(1, 2, 4.5, 5.5);
return 0;
}
调用foo()
会推断Type1
为空,Type2
为{int, int, double, double}
,而我希望Type1
为{int, int}
,Type2
为{double, double}
。如果不涉及std::tuple
,只调用上面代码中的foo()
函数,这可能吗?
编辑:
为了更清楚地说明我想要实现什么,这里有一个解释。我想创建一个函数,用户可以每次以偶数对的方式传递任意数量的两种类型变量。假设foo(Type1 x, Type1 y, Type1 z, Type1 ..., Type2 XX, Type2 YY, Type2 ZZ, Type2 ...);
,Type1
的变量将始终是const
引用,而Type2
的变量只是引用,因此函数将以以下形式结束:foo(const Type1& x, const Type1& y, ..., Type2& XX, Type2& YY, ...)
。在函数中,我将使用Type1
变量进行一些计算,并通过Type2
变量返回相应的结果。我知道使用任何容器结构都会让我的生活更轻松,但不幸的是,我不能接受这种解决方案。所以,虽然我不是一个经验丰富的人,但我认为使用变差函数是可行的,对吗?
不,编译器无法读懂你的想法。
你可以把一包类型分成两半:
template<class...>struct types{using type=types;};
template<class lhs, class rhs>struct cat;
template<class lhs, class rhs>using cat_t=typename cat<lhs,rhs>::type;
template<class...lhs, class...rhs>
struct cat<types<lhs...>,types<rhs...>>:
types<lhs...,rhs...>
{};
template<class types, size_t n>
struct split {
private:
using s0 = split<types,n/2>;
using r0 = typename s0::lhs;
using r1 = typename s0::rhs;
using s1 = split<r1,n-n/2>;
using r2 = typename s1::lhs;
public:
using lhs = cat_t<r0,r2>;
using rhs = typename s1::rhs;
};
template<class Types>
struct split<Types, 0>{
using lhs=types<>;
using rhs=Types;
};
template<class T0,class...Ts>
struct split<types<T0,Ts...>,1>{
using lhs=types<T0>;
using rhs=types<Ts...>;
};
然后我们使用它将foo
参数拆分为两个包:
template<class types>
struct foo2_t;
template<class... T0s>
struct foo2_t<types<T0s...>>{
template<class... T1s>
void operator()(T0s&&... t0s, T1s&&... t1s) const {
std::cout << sizeof...(T0s) << 'n';
std::cout << sizeof...(T1s) << 'n';
}
};
template <class... Ts>
void foo(Ts&&... ts) {
using s = split< types<Ts...>, sizeof...(Ts)/2 >;
foo2_t<typename s::lhs>{}( std::forward<Ts>(ts)... );
}
实例
如果你想让编译器做不同的魔术(比如,在相同的类型上聚集,或者你想做的任何其他事情),一种不同的(但相似的)技术会起作用。
尝试更简单的方法。以两个向量作为自变量。
template<typename T, typename A>
void foo( std::vector<T,A> const& t1, std::vector<T,A> const& t2 ) {
//do wtever you want
}
相关文章:
- 测试两个类型列表中的所有组合
- 如何更好地检查两个 char 变量是否在一组值中?
- 计算两个uint8_t变量之间差值的最快方法是什么?
- 如何查看两个字符变量是否相等
- 将包含多个类型变量的 PVOID 数组传递给 _beginthreadex()
- 为什么两个字符串文字可以连接,而不能连接两个字符串变量
- 在C 中使用两个CHAR变量评估布尔值
- 如何超载分配运算符,该操作员总计两个实例变量
- 正在检查两个TDateTime变量
- 两个条件变量和避免死锁
- 在C++中组合两个类型为T的数组
- 如何在不实例化两个c++类型的情况下确定这两个类型
- 线程同步:等待两个bool变量
- 这两个类型定义有什么区别?
- 使用共享指针在两个类型模板化类之间进行强制转换
- 交换类型列表中的两个类型
- C++在派生类和基类中使用两个同名变量
- 两个SYSTEMTIME变量之间的差异
- 具有不同const限定符的两个类型之间的转换
- 在 c++ 中使用 strcmp 比较两个 char 变量显示从 'char' 到 'const char*' 的无效转换