Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

c++ - 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.

if it is possible of course

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

then

get one less argument inside the function to use it inside the 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.

question from:https://stackoverflow.com/questions/65935047/if-there-is-such-a-function-in-a-variadic-template

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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__ << '
';
    printAllButLastHelper(
        std::make_integer_sequence<size_t, sizeof...(args)>{}, 
        std::forward<T>(args)...);
    std::cout << '
';
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...