【问题标题】:If there is such a function in a variadic template?如果可变参数模板中有这样的功能?
【发布时间】:2021-01-28 10:15:38
【问题描述】:

比如有这样的模板

template<class ... Types> void f(Types ... args);

f();       // OK: args contains no arguments
f(1);      // OK: args contains one argument: int
f(2, 1.0); // OK: args contains two arguments: int and double

我想在里面这样做

template<class ... T>
void f2(T... args) {
  // option 1
  // > hello // world // human
  std::cout <<(args / ...);

  // option 2
  // > hello // world
  std::cout <<((args / ...) and -1 args); // ../
}

在示例中,选项 2 我们正在连接Helloworld 字符串,同时不使用human,因为我们还不需要它。

当然可以

f2("hello", "world", "human");

然后

在函数内部少一个参数以在函数内部使用它

本次通话:

f2("A", "b", 12);

预期的结果应该是这样的:

std::cout << "A";
std::cout << "b";

// no statement or different action for: std::cout << 12;

如果可能的话,不用数组和递归 如果没有这样的功能,那么写它不存在。

【问题讨论】:

  • 您想对所有参数应用一些东西吗?比如逐个打印?
  • 是的,我想单独获取函数内部的每个参数,或者通过加或减一
  • 虽然我在调用 3 个参数时写,但在函数内部我想在 if 条件中使用 2 个参数,在第二个条件中我将使用 3 个参数
  • @DoydgonK。在您对我的回答发表评论后,您的问题变得更加清晰。所以我改进了你的问题(所以任何人都可以理解),我发现了各自的重复。
  • 我觉得副本已经过时了,7年前写的,代码很多:)

标签: c++ c++20


【解决方案1】:
template<bool condition, typename T>
void printIf(T&& arg)
{
    if constexpr (condition) std::cout << arg;
}

template<size_t...indexes, class ... T>
void printAllButLastHelper(std::integer_sequence<size_t, indexes...> v, T&&... args) {
    (printIf<sizeof...(args) - 1 != indexes>(args), ...);
}

template<class ... T>
void f2(T&&... args) {
    std::cout << __PRETTY_FUNCTION__ << '\n';
    printAllButLastHelper(
        std::make_integer_sequence<size_t, sizeof...(args)>{}, 
        std::forward<T>(args)...);
    std::cout << '\n';
}

https://godbolt.org/z/3dojcd

【讨论】:

    猜你喜欢
    • 2016-06-27
    • 2014-07-29
    • 2014-09-08
    • 2013-09-14
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多