如何在 C++ 中为偶数位置做可变参数模板?
How to do variadic template for even position in c++?
我必须编写一个可变参数模板函数,如果每个偶数位置的值都低于下一个位置的参数值,则该函数 returns 为真。
例子:
f(4, 5, 7, 9, 2, 4) -> 真 (4 < 5, 7 < 9, 2 < 4)
我试过这个:
template<typename T>
T check()
{
auto even_number = [](T x)
{ return (x % 2) == 0 ? x : 0; };
}
template <typename T, typename... A>
bool check(T first, A... args)
{
return first < check(args...) ? true : false;
}
int main()
{
std::cout << check(4, 5, 7, 9, 2, 4);
}
这个程序给我这些错误:
1.'check' : 没有找到匹配的重载函数
2.'T check(void)':无法推断 T 的模板参数 -> 如果我在第二个模板中添加“T check(T first, A... args)”,则会出现此错误
#include <iostream>
template <typename ... Ints>
constexpr bool check( Ints... args) requires(std::is_same_v<std::common_type_t<Ints...>, int> && sizeof... (Ints) %2 == 0)
{
int arr[] {args...};
for(size_t i{}; i < sizeof... (args)/2; ++i){
if (!(arr[2*i] < arr[2*i + 1])) return false;
}
return true;
}
int main()
{
std::cout << check(4, 3, 7, 9, 2, 4);
}
requires(std::is_same_v<std::common_type_t<Ints...>> && sizeof... (Ints) %2 == 0)
确保输入的数量是偶数并且是整数
递归版本
template <typename Int, typename ... Ints>
constexpr bool check(Int int1,Int int2, Ints... ints)requires(std::is_same_v<std::common_type_t<Int, Ints...>, int> && sizeof... (Ints) %2 == 0)
{
if constexpr (sizeof... (Ints) == 0) return int1 < int2;
else return int1 < int2 && (check(ints...));
}
假设参数个数总是偶数,你可以这样简单地做到:
bool check() {
return true;
}
template <typename T, typename... Ts>
bool check(T t1, T t2, Ts... ts) {
return t1 < t2 && (check(ts...));
}
我必须编写一个可变参数模板函数,如果每个偶数位置的值都低于下一个位置的参数值,则该函数 returns 为真。 例子: f(4, 5, 7, 9, 2, 4) -> 真 (4 < 5, 7 < 9, 2 < 4)
我试过这个:
template<typename T>
T check()
{
auto even_number = [](T x)
{ return (x % 2) == 0 ? x : 0; };
}
template <typename T, typename... A>
bool check(T first, A... args)
{
return first < check(args...) ? true : false;
}
int main()
{
std::cout << check(4, 5, 7, 9, 2, 4);
}
这个程序给我这些错误: 1.'check' : 没有找到匹配的重载函数 2.'T check(void)':无法推断 T 的模板参数 -> 如果我在第二个模板中添加“T check(T first, A... args)”,则会出现此错误
#include <iostream>
template <typename ... Ints>
constexpr bool check( Ints... args) requires(std::is_same_v<std::common_type_t<Ints...>, int> && sizeof... (Ints) %2 == 0)
{
int arr[] {args...};
for(size_t i{}; i < sizeof... (args)/2; ++i){
if (!(arr[2*i] < arr[2*i + 1])) return false;
}
return true;
}
int main()
{
std::cout << check(4, 3, 7, 9, 2, 4);
}
requires(std::is_same_v<std::common_type_t<Ints...>> && sizeof... (Ints) %2 == 0)
确保输入的数量是偶数并且是整数
递归版本
template <typename Int, typename ... Ints>
constexpr bool check(Int int1,Int int2, Ints... ints)requires(std::is_same_v<std::common_type_t<Int, Ints...>, int> && sizeof... (Ints) %2 == 0)
{
if constexpr (sizeof... (Ints) == 0) return int1 < int2;
else return int1 < int2 && (check(ints...));
}
假设参数个数总是偶数,你可以这样简单地做到:
bool check() {
return true;
}
template <typename T, typename... Ts>
bool check(T t1, T t2, Ts... ts) {
return t1 < t2 && (check(ts...));
}