使函数仅获取每对存在的第一个值
Making a function take only the first value from every pair present
我需要使一个函数仅获取每个传递给其参数的每个 std::pair
的第一个值。不使用std::pair
类型的值将不变。我的以下解决方案仅适用于需要两个参数的函数。我需要知道如何将其推广到任何数量的参数。
#include <type_traits>
template <typename T, typename = void>
struct has_first_type : std::false_type { };
template <typename T>
struct has_first_type<T, std::void_t<typename T::first_type>> : std::true_type { };
template <typename R, typename T, typename U, typename = void> struct act_on_first;
template <typename R, typename T, typename U>
struct act_on_first<R, T, U, std::enable_if_t<has_first_type<T>::value && has_first_type<U>::value>> {
template <typename F>
static R execute (const T& t, const U& u, F f) {
return f(t.first, u.first);
}
};
template <typename R, typename T, typename U>
struct act_on_first<R, T, U, std::enable_if_t<has_first_type<T>::value && !has_first_type<U>::value>> {
template <typename F>
static R execute (const T& t, const U& u, F f) {
return f(t.first, u);
}
};
template <typename R, typename T, typename U>
struct act_on_first<R, T, U, std::enable_if_t<!has_first_type<T>::value && has_first_type<U>::value>> {
template <typename F>
static R execute (const T& t, const U& u, F f) {
return f(t, u.first);
}
};
template <typename R, typename T, typename U>
struct act_on_first<R, T, U, std::enable_if_t<!has_first_type<T>::value && !has_first_type<U>::value>> {
template <typename F>
static R execute (const T& t, const U& u, F f) {
return f(t, u);
}
};
struct foo {
template <typename... Args>
std::size_t operator()(Args&&...) { return sizeof...(Args); } // Simple example only.
};
template <typename T, typename U>
std::size_t bar (const T& t, const U& u) {
return act_on_first<std::size_t, T, U>::execute(t, u, foo());
}
// Testing
#include <iostream>
int main() {
std::pair<int, bool> k = {3, true};
std::pair<int, char> m = {5, 't'};
std::cout << bar(k,m) << 'n'; // 2
std::cout << bar(k,5) << 'n'; // 2
std::cout << bar(3,m) << 'n'; // 2
std::cout << bar(3,5) << 'n'; // 2
}
写一个变压器,要么给您 .first
for pairs,要么只是返回其参数:
template <typename T> T const& take_first(T const& x) { return x; }
template <typename T, typename U>
T const& take_first(std::pair<T, U> const& p) { return p.first; }
template <typename... Args>
std::size_t bar(Args const&... args) {
return foo{}(take_first(args)...);
}
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 在我的第一个C++程序中需要一些帮助(简单)
- 为什么我的代码在第一个 if 语句处中断?
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 无法使我的第一个Windows OpenGL窗口抬起并运行
- 将参数初始化为构造函数,而不是第一个
- 使函数仅获取每对存在的第一个值