Rasmus-123
Rasmus-123

Reputation: 81

How do I make sure Types in a variadic Tuple are identical?

I want to create a toString function for Tuples with a variadic amount of a specific type (arithmetic types for now).

Something like this

<template T, typename enable_if<is_arithmetic_v<T>>::type* = nullptr>
toString(tuple<T...> tup) 
{ 
    std::stringstream ss;
    std::apply([&ss](auto&&... args) {((ss << args << ";"), ...); }, tup);
    return ss.str();
}

where all members are the same type and the type is a number type.

I found this, but that allows all types and mixed tuples like make_tuple("str", 12.0f, 123).

Could someone explain how I'd do that in C++17?

Thanks :)

Upvotes: 4

Views: 115

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

You can check all the types are identical or not with the help of fold expression (since C++17).

E.g.

template <typename T,                                                       // the 1st type 
          typename... Args,                                                 // subsequent types
          typename enable_if<is_arithmetic_v<T>>::type* = nullptr,          // check for arithmetic type
          typename enable_if<(is_same_v<T, Args> && ...)>::type* = nullptr> // check all the types are identical or not
auto toString(tuple<T, Args...> tup) 
{ 
    std::stringstream ss;
    std::apply([&ss](auto&&... args) {((ss << args << ";"), ...); }, tup);
    return ss.str();
}

LIVE

Upvotes: 3

Related Questions