I'm currently creating some utilities for my projects, and I came up with the idea to replicate the C# Action
class in C . As you can see in the C# documentation, the Action
class can have different "overloads" with templates. It has Action
, Action<T1>
, Action<T1, T2\>
, etc.
Is it possible to overload classes like this in C ? Or, is there any workaround?
This is an example of "pseudocode", C throws a syntax error with this:
class Action
{
// Code
};
template<class T1>
class Action
{
// Code
};
template<class T1, class T2>
class Action
{
// Code
};
// etc...
So that you can call different kinds of classes depending if you input a template or not, like this:
int main()
{
Action a1;
Action<int> a2;
Action<int, float> a3;
// etc...
return 0;
}
I tried various things, such as:
template<T1, T2>
class Action {};
template<T1, T2>
class Action<T1.> {};
template<T1, T2>
class Action<T1, T2> {};
But this does not work.
CodePudding user response:
No, classes can't be overloaded. Action
in the scope can be either a single non-templated class or a single class template with a given template head (not different ones).
But, a given class template can be specialized for certain template arguments and there are variadic templates since C 11 which accept an arbitrary number of template arguments:
template<typename... Ts>
class Action { /* generic case */ };
This allows for a2
and a3
and via explicit or partial specialization they can be specialized for e.g. one or two template arguments:
template<typename T1>
class Action<T1> { /* one template argument */ };
template<typename T1, typename T2>
class Action<T1, T2> { /* two template arguments */ };
a1
can also work since C 17 via class template argument deduction (CTAD) depending on which constructors the primary class template has and/or what deduction guides are declared.
I don't have enough knowledge of C# or context to know whether this is a useful approach to take for your underlying problem though.
Also, as a side note: class
and typename
when introducing template parameters in the template head are synonymous. Choose class
if you prefer that. There is no difference.