Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 238
  • Last Modified:

Many templates for a class.

Hi,

Is there anyway to achieve something as in the following code, where vars 2 and 3 are only used if that specific template is used?

Thanks,
Uni.
template<typename A>
template<typename A, typename B>
template<typename A, typename B, typename C>
class CMyClass{
       A var1;
       B var2;
       C var3;
};

Open in new window

0
Unimatrix_001
Asked:
Unimatrix_001
  • 2
1 Solution
 
jkrCommented:
No, this won't work that way, sorry. There's the possibility to use default parameters, but no way to have them default to 'not present'.
0
 
Unimatrix_001Author Commented:
Ah, I was afraid of such. :(

Thank you.
Uni
0
 
evilrixSenior Software Engineer (Avast)Commented:
A work around is to use a "NoArg" flag that is used as the default parameter. The flag is just an empty struct. Of course, if you then write code that instantiates a concrete template that tries to use the NoArg flag in anyway that is erroneous you'll get a compile time error. This is the solution Boost often uses to simulate variable argument templates.
struct NoArg {};
 
template<typename A, typename B = NoArg, typename C = NoArg>
class CMyClass{
       A var1;
       B var2;
       C var3;
};
 
int main()
{
	CMyClass<int> ci;
	CMyClass<int, float> cif;
	CMyClass<int, float, long> cifl;
}

Open in new window

0
 
Unimatrix_001Author Commented:
Hm... I think I'll just wait for C++0x and the variadic templates (I think that's the correct name...). ;)

Thanks,
Uni
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now