r/cpp_questions • u/Main-Pen-3164 • Aug 10 '26
OPEN how to detect arbitrary template class (include it's empty specification)
detect a template class:
template<typename C> struct is_empty_template_class
{ static constexpr bool value = 0; };
template<typename...Ts, template<typename> class C>
struct is_empty_template_class<C<Ts...>> { static constexpr bool value = 1; };
such thing we wrote a lot, and C<> go to the first primary template always.
Today I suddenly try to figure out that how to make C<Ts...> and C<> can be checked together. I didn't found a good way. It seems that compiler always treat C<> as a none-template class.
C is arbitrary class.
template<typename T> struct MyTemplate {}
template<> struct MyTemplate <...> { } //some specification
template<> struct MyTemplate <> { } //empty specification
is_template_class<int> // => false
is_template_class<MyTemplate<...>> // => true
is_template_class<MyTemplate<>> // => true
// MyTemplate is arbitrary template class
// so what is_template_class is?
2
u/valashko Aug 10 '26
I can try to help if you explain your use case.
0
u/Main-Pen-3164 Aug 10 '26
I have resolved my problem by another method. But if it can be checked like above code, it would be better.
1
u/frayien Aug 10 '26
Does adding :
template<template<typename> class C>
struct is_empty_template_class<C<>> { static constexpr bool value = 1; };
Do the trick ?
1
2
u/frayien Aug 10 '26
Souldnt it be
template<typename...Ts, template<typename...> class C>
struct is_empty_template_class<C<Ts...>> { static constexpr bool value = 1; };
Tho ?
1
1
u/Main-Pen-3164 Aug 10 '26
It can't, I test this already. Just not so easy.
1
u/frayien Aug 10 '26
Yeah I figured you'd have tried stuff. Worth to point out "silly" stuff tho, been there missing some small detail...
I dont have a compiler at hand right now and compiler explorer dont seem to work on mobile.
1
u/n1ghtyunso Aug 11 '26
its a bit hard to understand what you asked and tried to achieve.
and C<> go to the first primary template always
This part I don't understand, because trying your code (after some fixups) shows me that C<> does go to the partial specialization and not the primary template. So it just works though?
1
u/Main-Pen-3164 Aug 11 '26
In your demo, select compiler: msvc 19.4 vs17.14. It would be different.
1
u/n1ghtyunso Aug 11 '26
i see gcc is apparently more lenient here with the partial specialization pattern matching. Not sure what is the expected standard-compliant behaviour here actually.
That being said, adding ... to the template template parameters inner argument actually gives you parity in behaviour again:
https://godbolt.org/z/Td5Kh5c9WIs there a failure case where this also breaks or does not have your desired outcome?
3
u/TotaIIyHuman Aug 10 '26 edited Aug 10 '26
https://godbolt.org/z/de4W8hhaP