3

I'm asking myself

Can you write a class template and a corresponding partial specialization such that for any set of template arguments for the parameters, the partial specialization is taken by the compiler?

For example

template<typename T>
struct A { };

template<typename T>
struct A</* what to write!?*/> { };

I seem to remember having read that this is possible somehow, but I forgot the exact algorithm to make this work.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • I'm somehow confused how this would be a *partial* specialization if for *any* arguments it should take that very definition? Or am I misunderstanding the question? – Janick Bernet Oct 15 '11 at 00:26
  • @inflagranti it's just called partial specialization. In this particular case it would accept any argument. Just like a template can be made to accept only one argument by using SFINAE tricks but it's still called a template. – Johannes Schaub - litb Oct 15 '11 at 00:34
  • The point I was trying to make is, that if it accepts any type, there is no difference from the so called specialization to the unspecialised, generic template, hence it is not very useful. But I guess this is mainly a thought experiment anyway, right? :) – Janick Bernet Oct 15 '11 at 00:42
  • @litb, You don't consider SFINAE trick a partial specialization for this question ? – iammilind Oct 15 '11 at 02:24
  • @iammilind you are allowed to use whatever you like in order to solve this question. But there is a very easy C++03 solution that doesn't need SFINAE. – Johannes Schaub - litb Oct 15 '11 at 02:26

2 Answers2

4

My version of GCC is happy to accept:

template<typename T>
struct A;

template<typename... Pack>
struct A<Pack...> {};
Luc Danton
  • 34,649
  • 6
  • 70
  • 114
2

If you allow SFINAE trick then, it will be as easy as this:

enum E { TRUE };

template<typename T, E = TRUE>
struct A
{
  static const bool value = false;
};

template<typename T>
struct A<T, TRUE>
{
  static const bool value = true;
};

Demo.

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • 1
    The wording is very carefully crafted: 'any set of template arguments'. This includes arguments that can be defaulted: for instance your specialization doesn't match `A`. – Luc Danton Oct 15 '11 at 03:44
  • @LucDanton, check the updated answer. Now it should work for anything (if dirty typecasting is not used; i.e. `A`). – iammilind Oct 15 '11 at 04:28
  • Well, how dirty *is* that casting though? Enumeration types have a valid range of values that is (usually) larger than the set of all enumerators! Since the exact rules that determinate that range for such an enum definition are quite complicated, I'd be interested if you can demonstrate that an implementation is allowed to have { 0 } as the set of values of `E`. My interpretation is that the set cannot be smaller than { 0, 1 }. – Luc Danton Oct 15 '11 at 04:44