简体   繁体   English

如果可变参数模板中有这样的function?

[英]If there is such a function in a variadic template?

for example there is such a template例如有这样一个模板

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

and I want to do so in it我想在里面这样做

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); // ../
}

in the example, option 2 We are concatenating the Hello and world string and at the same time not using the human , since we don't need it yet.在示例中,选项 2 我们正在连接Helloworld字符串,同时不使用human ,因为我们还不需要它。

if it is possible of course如果有可能当然

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

then然后

get one less argument inside the function to use it inside the function在 function 中少取一个参数以在 function 中使用它

For this call:对于这个电话:

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

Expected result should be equivalent to this:预期结果应该等同于:

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

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

and if possible without arrays and recursions if there is no such functionality, then write that it is not there.如果可能没有 arrays 和递归,如果没有这样的功能,那么写它不存在。

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 https://godbolt.org/z/3dojcd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM