Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How can I get the type in a C++17 fold function?

132 views
Skip to first unread message

Mut...@dastardlyhq.com

unread,
Dec 8, 2022, 4:49:01 AM12/8/22
to
eg:

template<typename... T>
auto sum(T&&... args)
{
if (typeid(T) == typeid(string)) { do something }
return (args + ...);
}

However doing typeid on T gives

error: expression contains unexpanded parameter pack 'T'

in clang.

Is there a way to get the type inside the function?

Juha Nieminen

unread,
Dec 8, 2022, 7:19:10 AM12/8/22
to
The problem is that T there is not a type, but a parameter pack.
You can't 'typeid(T)' when T is a parameter pack (what would that
even mean? A parameter pack is essentially a bunch of types).

If you want to iterate through all the types in that parameter
pack and do one thing or another depending on a particular type,
you'll need to do it in the more "traditional" C++11 way of
iterating parameter packs. In other words, something along the
lines of:

void doSomething(const std::string& s) { /* ... */ }

template<typename T>
void doSomething(const T&) {}

template<typename First>
auto sum(First&& first) { return first; }

template<typename First, typename... Rest>
auto sum(First&& first, Rest&&... rest)
{
doSomething(first);
return first + sum(std::forward<Rest>(rest)...);
}

Öö Tiib

unread,
Dec 8, 2022, 7:46:06 AM12/8/22
to
There are too lot of ways but I usually check the types in enable_if
as I've used to see that and all compilers can already process that.
If needed I make checking templates myself.

#include <iostream>
#include <string>

// make checking for char array type
template <class> struct is_bounded_char_array : std::false_type {};
template <size_t N> struct is_bounded_char_array<char[N]> : std::true_type {};

// if not std::string, char* and char array
template<typename T,
std::enable_if_t<
!std::is_same_v<std::string, T>
&& !std::is_same_v<char*, T>
&& !is_bounded_char_array<T>{}
, bool> = true>
// return whatever it is without processing
auto process_value(T const& v) {return v;}

// for things disabled above return result of string to double conversion
// or whatever your "do something" means
double process_value(std::string const& s) { return std::stod(s); }

// now your sum is simple to write
template<typename... T>
auto sum(T&&... args) {return (process_value(args) + ...); }

// and demo should output 10
int main()
{
char arr[] = "1";
char* ptr = arr;
std::cout << sum(ptr, 2, "3.0", std::string("4")) << "\n";
}

Mut...@dastardlyhq.com

unread,
Dec 8, 2022, 10:41:37 AM12/8/22
to
Thats just variadic templates with a slightly different syntax. AFAIK the
point of folds is not having to manually iterate the arguments yourself as
with 2011 which is little better than C's varargs (and probably less efficient
due to recursion vs pointer incrementing).

Mut...@dastardlyhq.com

unread,
Dec 8, 2022, 10:46:07 AM12/8/22
to
Clearly you know more about the dustier corners of C++ than me. enable_if is
the only one of those tests I've heard of.

Öö Tiib

unread,
Dec 8, 2022, 4:59:57 PM12/8/22
to
Oh there are quite lot of those checks in C++ metaprogramming.
<https://en.cppreference.com/w/cpp/meta> is good reference of those.
I often do not remember what standard was one or other added but
some important things are still built with older compilers so then
I look from there.

It is good site but tricky to support them ... as I don't need
much geeky merchantise where their "support" link leads.:D



Juha Nieminen

unread,
Dec 9, 2022, 7:58:13 AM12/9/22
to
Well, if you can come up with a fold expression that does what you want,
go right ahead.

Vir Campestris

unread,
Dec 14, 2022, 5:42:57 AM12/14/22
to
Surely the right way to code this is with an explicit specialisation

template<> auto sum(string&& args)

rather than a runtime check?

Andy

Bonita Montero

unread,
Dec 14, 2022, 12:02:18 PM12/14/22
to
This makes the check for each variable:

#include <iostream>
#include <type_traits>

using namespace std;

int main()
{
auto variadic = []<typename ... Args>( Args &&... args )
{
auto onString = []<typename T>( T &&t )
{
if constexpr( is_same_v<remove_cvref_t<T>, string> )
cout << t << endl;
};
(onString( forward<Args>( args ) ), ...);
};
variadic( string( "hello world"), 123 );
}

Mut...@dastardlyhq.com

unread,
Dec 14, 2022, 12:17:28 PM12/14/22
to
Arrrgh!

[Runs screaming to the hills...]

Bonita Montero

unread,
Dec 14, 2022, 12:23:03 PM12/14/22
to
If you know the lanuguage this is easy to read.

Bonita Montero

unread,
Dec 15, 2022, 11:58:52 AM12/15/22
to
Am 08.12.2022 um 10:48 schrieb Mut...@dastardlyhq.com:
This is exactly what you're looking for.
The first parameter of the outer lambda call is
checked if it is a string and if it is it is cout'ed:

#include <iostream>
#include <concepts>
#include <type_traits>

using namespace std;

int main()
{
auto variadic = []<typename ... Args>( Args &&... args )
{
auto unroll = [&]<size_t Index, size_t ... Indices>(
integral_constant<size_t, Index>, index_sequence<Indices ...> )
{
auto onString = []<typename T>( T &&t )
{
if constexpr( is_same_v<remove_cvref_t<T>, string> )
cout << t << endl;
};
((Indices == Index ? onString( forward<Args>( args ) ) : (void)0), ...);
};
unroll( integral_constant<size_t, 0>(), make_index_sequence<sizeof
...(args)>() );

Mut...@dastardlyhq.com

unread,
Dec 15, 2022, 12:20:48 PM12/15/22
to
>....(args)>() );
> };
> variadic( string( "hello world"), 123 );
>}

I don't even know what some of those meta functions do. index_sequence,
remove_cvref_t anyone?

It would have been nice if the committee had simply added a way to get the
type of the current argument. Perhaps "typeid(args[0])". They've fucked with
the syntax so much already that overloading [] again wouldn't make much
difference.

Bonita Montero

unread,
Dec 15, 2022, 12:37:41 PM12/15/22
to
Am 15.12.2022 um 18:20 schrieb Mut...@dastardlyhq.com:

> It would have been nice if the committee had simply added a way to get the
> type of the current argument. Perhaps "typeid(args[0])". They've fucked with
> the syntax so much already that overloading [] again wouldn't make much
> difference.

This is just an example. There's almost never a need to get the type of
a variadic argument by index.

Bonita Montero

unread,
Dec 15, 2022, 11:26:37 PM12/15/22
to
Now I found a really simple solution:

#include <iostream>
#include <concepts>
#include <type_traits>

using namespace std;

int main()
{
auto variadic = []<typename ... Args>( Args &&... args )
{
auto tupl = make_tuple( ref( args ) ... );
if constexpr( requires( decltype(tupl) tpl ) { { get<0>( tpl ) }; } )
{
auto &firstElem = get<0>( tupl );
if constexpr( is_same_v<remove_cvref_t<decltype(firstElem)>, string> )
cout << firstElem << endl;

Bonita Montero

unread,
Dec 15, 2022, 11:40:55 PM12/15/22
to
Now it's so simple that anyone should understand this:

#include <iostream>
#include <concepts>
#include <type_traits>

using namespace std;

int main()
{
auto variadic = []<typename ... Args>( Args &&... args )
{
if constexpr( sizeof ...(Args) >= 1 )
{
auto tupl = make_tuple( ref( args ) ... );

Scott Lurndal

unread,
Dec 16, 2022, 10:17:29 AM12/16/22
to
int main()
{ printf("hello world\n");
}

Is far simpler. Complexity is evil.


"While complexity seeks order through addition, simplicity
seeks it through subtraction. Most people have a built-in bias
toward addition instead of subtraction. For some reason, the
concept of more comes naturally to us."

Bonita Montero

unread,
Dec 16, 2022, 12:22:39 PM12/16/22
to
Am 16.12.2022 um 16:17 schrieb Scott Lurndal:
> Bonita Montero <Bonita....@gmail.com> writes:
>> Now it's so simple that anyone should understand this:
>>
>> #include <iostream>
>> #include <concepts>
>> #include <type_traits>
>>
>> using namespace std;
>>
>> int main()
>> {
>> auto variadic = []<typename ... Args>( Args &&... args )
>> {
>> if constexpr( sizeof ...(Args) >= 1 )
>> {
>> auto tupl = make_tuple( ref( args ) ... );
>> auto &firstElem = get<0>( tupl );
>> if constexpr( is_same_v<remove_cvref_t<decltype(firstElem)>, string> )
>> cout << firstElem << endl;
>> }
>> };
>> variadic( string( "hello world"), 123 );
>> }
>
> int main()
> { printf("hello world\n");
> }
>
> Is far simpler. Complexity is evil.

It wasn't the job to print out hello world. This was just to show
that what I was actually trying to achieve is working. Show me a
simpler solution to check if the first variadic parameter exists
and it is a string-object.

Scott Lurndal

unread,
Dec 16, 2022, 12:42:58 PM12/16/22
to
Why? Of what usefulness would it be in real-world code? It
remains unnecessary complexity.

Bonita Montero

unread,
Dec 16, 2022, 1:20:38 PM12/16/22
to
Am 16.12.2022 um 18:42 schrieb Scott Lurndal:

> Why? Of what usefulness would it be in real-world code?

I didn't ask for that.

> It remains unnecessary complexity.

If you have this problem, then I think this is the simplest solution.
People on Stack Overflow don't have any issues with that, but here
the people act like rebels.

Tim Rentsch

unread,
Dec 28, 2022, 7:41:23 PM12/28/22
to
sc...@slp53.sl.home (Scott Lurndal) writes:

> "While complexity seeks order through addition, simplicity
> seeks it through subtraction. Most people have a built-in bias
> toward addition instead of subtraction. For some reason, the
> concept of more comes naturally to us."

It appears the original source of this quote is here:

https://uxdesign.cc/the-quest-for-simplicity-5c31ae2c553f

I encourage people to read the article. Not that I think what it
says is deep or profound, I don't, but I think people might be
interested to read it.

Bonita Montero

unread,
Dec 28, 2022, 9:39:39 PM12/28/22
to
Am 29.12.2022 um 01:41 schrieb Tim Rentsch:

> It appears the original source of this quote is here:
>
> https://uxdesign.cc/the-quest-for-simplicity-5c31ae2c553f
>
> I encourage people to read the article. Not that I think what
> it says is deep or profound, I don't, but I think people might
> be interested to read it.

And how does this make my example simpler ?

Tim Rentsch

unread,
Dec 29, 2022, 1:27:37 AM12/29/22
to
I quoted all the text that was relevant to what I was saying.
You may notice that your name and your example did not appear in
the quoted text in any way.

Paavo Helde

unread,
Dec 29, 2022, 2:36:17 AM12/29/22
to
I guess that's how we arrive to "simple" user interfaces like unclear
amount of white borderless text boxes on white background, some of which
are maybe editable and some of which are maybe empty.

And then there are these phone apps which require unknown amount of hand
gestures of unknown types, in unknown place, for interaction. But the
interface looks simple.

Mason

unread,
Dec 29, 2022, 12:21:36 PM12/29/22
to
On 29/12/2022 07:36, Paavo Helde wrote:
>
>
>
> And then there are these phone apps which require unknown amount of
> hand gestures of unknown types, in unknown place, for interaction. But
> the interface looks simple.

We are going back to the good old days of "hieroglyphics". The
Egyptians would be proud of us copying them.





Alf P. Steinbach

unread,
Dec 29, 2022, 1:11:43 PM12/29/22
to
It's a bit off topic this. But:

one main reason things get even more unusable by the quarter-year, is
that the designers are conflating "simple to use" with "looks simple".

They are intellectually unable to grok "simple to use", because they are
primarily selected for their ability to follow and to some degree be in
the forefront of trends of popularity, secondly for their ability to put
down hard repetitious work and work long hours, and third for their
ability to sometimes be slightly creative as long as it is within
established popular trends; they're not selected for intelligence and
critical thinking, which runs counter to the three main criteria, i.e.
would effectively be a disability for them.

Ultimately this depends on the consumers lacking a sense of quality and
rewarding conformity and whatever is noticeable without a thought, like
simple eye candy.

And they do.

Regarding "without a thought", an example a few months ago from the
local grocery store: in the meat disk one slot was full of steaks, none
sold, with price shown per kg., high, and the adjacent slot was nearly
empty, with just a few steaks left, with price shown per steak, a much
LOWER NUMBER -- it was a best-seller, but it was the exact same price
and the exact same product as the steaks that didn't sell.



- Alf

Tim Rentsch

unread,
Dec 29, 2022, 10:58:51 PM12/29/22
to
Yes, this is very much like my own reaction.

Bonita Montero

unread,
Dec 30, 2022, 2:09:03 AM12/30/22
to
Show me how to make that what I did with a simpler approach.
What I did isn't complex but just uncommon.

Michael S

unread,
Dec 30, 2022, 6:27:53 AM12/30/22
to
On Thursday, December 29, 2022 at 9:36:17 AM UTC+2, Paavo Helde wrote:
>
> And then there are these phone apps which require unknown amount of hand
> gestures of unknown types, in unknown place, for interaction. But the
> interface looks simple.

And somehow kids manage to cope. Isn't it a little wonder?

Alf P. Steinbach

unread,
Dec 30, 2022, 8:02:15 AM12/30/22
to
Kids try out things and are great at memorizing arbitrary stuff. They're
necessarily also vastly more smart than adults, in the sense of more
flexible thinking and self-adjustment, though without the knowledge base
that lets those smarts manifest as recognizable or measurable adult
level intelligence. So when the UI changes (new phone, update, whatever)
they just try out things and memorize the new ways, plus they
communicate about such things so they can learn from other kids.

Adults rely more on a fixed established knowledge base, and the ability
to apply a once learned set of rules to figure out how to do things, and
many adults are prevented socially (I'll look dumb if I ask! I'm afraid
of being put down!) from communicating much about such things.

An adult will explore but systematically, in accordance with the once
learned rules, where kids will explore more at random. An adult has
expectations, and can have "WTF?" reactions and back off, where a kid
just happily accepts whatever happens and doesn't limit itself to what
an adult may think is sensible.


- Alf

Mut...@dastardlyhq.com

unread,
Dec 30, 2022, 10:17:32 AM12/30/22
to
On Fri, 30 Dec 2022 14:01:56 +0100
"Alf P. Steinbach" <alf.p.s...@gmail.com> wrote:
>On 30 Dec 2022 12:27, Michael S wrote:
>> On Thursday, December 29, 2022 at 9:36:17 AM UTC+2, Paavo Helde wrote:
>>>
>>> And then there are these phone apps which require unknown amount of hand
>>> gestures of unknown types, in unknown place, for interaction. But the
>>> interface looks simple.
>>
>> And somehow kids manage to cope. Isn't it a little wonder?
>
>Kids try out things and are great at memorizing arbitrary stuff. They're
>necessarily also vastly more smart than adults, in the sense of more

Anyone who has kids knows thats not true. They're good at muscle memory
learning. Not always academic learning.

Jorgen Grahn

unread,
Dec 30, 2022, 12:31:26 PM12/30/22
to
On Fri, 2022-12-30, Alf P. Steinbach wrote:
> On 30 Dec 2022 12:27, Michael S wrote:
>> On Thursday, December 29, 2022 at 9:36:17 AM UTC+2, Paavo Helde wrote:
>>>
>>> And then there are these phone apps which require unknown amount of hand
>>> gestures of unknown types, in unknown place, for interaction. But the
>>> interface looks simple.
>>
>> And somehow kids manage to cope. Isn't it a little wonder?
>
> Kids try out things and are great at memorizing arbitrary stuff. They're
> necessarily also vastly more smart than adults, in the sense of more
> flexible thinking and self-adjustment, though without the knowledge base
> that lets those smarts manifest as recognizable or measurable adult
> level intelligence. So when the UI changes (new phone, update, whatever)
> they just try out things and memorize the new ways, plus they
> communicate about such things so they can learn from other kids.
>
> Adults rely more on a fixed established knowledge base, and the ability
> to apply a once learned set of rules to figure out how to do things, and
> many adults are prevented socially (I'll look dumb if I ask! I'm afraid
> of being put down!) from communicating much about such things.

And grumpy old programmers are more likely to

- want to know what's really going on
- want to know the extent of the feature set behind
the interface[1]
- know that the device may be their enemy
- have a distaste for magical thinking
- etc

> An adult will explore but systematically, in accordance with the once
> learned rules, where kids will explore more at random. An adult has
> expectations, and can have "WTF?" reactions and back off, where a kid
> just happily accepts whatever happens and doesn't limit itself to what
> an adult may think is sensible.

/Jorgen

[1] Personally I make an exception for Emacs. I have accepted that
there are whole subcontinents of features I haven't mapped.

As for C++ there's a lot I don't know, but I'm pretty sure I'm
not missing out on anything major.

--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .

Bonita Montero

unread,
Dec 30, 2022, 12:35:53 PM12/30/22
to
That's not a matter of reasoning.
Kids are just more open-minded than you.


Alf P. Steinbach

unread,
Dec 30, 2022, 2:05:14 PM12/30/22
to
Oh, they're good at anything, because mother Nature has designed them
for precisely that: to learn an extreme amount of things in a short
time, and to be able to survive without an adult's knowledge base. Brain
plasticity is maximal as a newborn. At some point the loss of plasticity
becomes critical also to ordinary thinking, so that e.g. mathematicians
don't in general produce anything noteworthy after age 35 or so.


- Alf

Chris M. Thomasson

unread,
Dec 30, 2022, 4:54:40 PM12/30/22
to
Oh shit. I am 45!

Mut...@dastardlyhq.com

unread,
Dec 31, 2022, 10:33:51 AM12/31/22
to
On Fri, 30 Dec 2022 20:04:58 +0100
"Alf P. Steinbach" <alf.p.s...@gmail.com> wrote:
>On 30 Dec 2022 16:17, Mut...@dastardlyhq.com wrote:
>> On Fri, 30 Dec 2022 14:01:56 +0100
>> "Alf P. Steinbach" <alf.p.s...@gmail.com> wrote:
>>> On 30 Dec 2022 12:27, Michael S wrote:
>>>> On Thursday, December 29, 2022 at 9:36:17 AM UTC+2, Paavo Helde wrote:
>>>>>
>>>>> And then there are these phone apps which require unknown amount of hand
>>>>> gestures of unknown types, in unknown place, for interaction. But the
>>>>> interface looks simple.
>>>>
>>>> And somehow kids manage to cope. Isn't it a little wonder?
>>>
>>> Kids try out things and are great at memorizing arbitrary stuff. They're
>>> necessarily also vastly more smart than adults, in the sense of more
>>
>> Anyone who has kids knows thats not true. They're good at muscle memory
>> learning. Not always academic learning.
>>
>
>Oh, they're good at anything, because mother Nature has designed them
>for precisely that: to learn an extreme amount of things in a short
>time, and to be able to survive without an adult's knowledge base. Brain

Knowing a lot of things is not the same as being smart - ie being able to
problem solve novel situations and grasping complex abstract scenarios.
Something many people, perhaps even the majority, don't seem to get as many
think someone who can parrot a load of Shakespeare or Descartes is some kind of
genius.

>plasticity is maximal as a newborn. At some point the loss of plasticity
>becomes critical also to ordinary thinking, so that e.g. mathematicians
>don't in general produce anything noteworthy after age 35 or so.

True, ditto musicians and artists. Perhaps programmers too but a lot of good
stuff has been produced by middle aged guys.

Tim Rentsch

unread,
Jan 2, 2023, 4:30:51 PM1/2/23
to
Jorgen Grahn <grahn...@snipabacken.se> writes:

> On Fri, 2022-12-30, Alf P. Steinbach wrote:
>
>> On 30 Dec 2022 12:27, Michael S wrote:
>>
>>> On Thursday, December 29, 2022 at 9:36:17 AM UTC+2, Paavo Helde wrote:
>>>
>>>> And then there are these phone apps which require unknown amount
>>>> of hand gestures of unknown types, in unknown place, for
>>>> interaction. But the interface looks simple.
>>>
>>> And somehow kids manage to cope. Isn't it a little wonder?
>>
>> Kids try out things and are great at memorizing arbitrary stuff.
>> They're necessarily also vastly more smart than adults, in the
>> sense of more flexible thinking and self-adjustment, [...]

Kids are better at fast thinking. Adults are better at slow
thinking. Very few people are good at both.

> And grumpy old programmers are more likely to
>
> - want to know what's really going on
> - want to know the extent of the feature set behind
> the interface[1]
> - know that the device may be their enemy
> - have a distaste for magical thinking
> - etc

I would say experienced programmers, whether or not they are
grumpy.

> [1] Personally I make an exception for Emacs. I have accepted
> that there are whole subcontinents of features I haven't
> mapped.

I would be surprised to hear of any person who had mapped the
entire emacs command set. Certainly I am not anywhere close to
knowing the extent of emacs geography, and I've been a regular
emacs user for more than 40 years.
0 new messages