I have the following piece of code. Let us have the function declaration and implementation seperate.
#include <iostream>
class Y1 {};
class Y2 {};
template <class T1, class T2>
class A
{
public:
explicit A();
void foo() const;
int bar() const;
};
template <class T1, class T2>
A<T1, T2>::A() {}
template <class T1, class T2>
void A<T1, T2>::foo() const {}
template <class T1, class T2>
int A<T1, T2>::bar() const {}
int main() {
A<Y1, Y2> a;
a.foo();
A<Y1, Y2> *a2 = new A<Y1, Y2>();
a2->foo();
return 0;
}
It is a pain every time writing
template <class T1, class T2>
for every object declaration and function declaration.
Can someone help with a macro or typedef to shorten the template parameters description.
In my own code I also separate the declaration from the implementation. Sometimes I just need the code to know that there exists a template, more often I want to make it very easy to see what the interfaces are.
I have solved this tedious typing with macros. However, the solution is complicated.
In case your return type does not have a comma (that is, excluding cases such as
std::unordered_map<int, std::string>
) here's a simple utility macro:You can use it like this:
and
You could have
TEMPLATE1
,TEMPLATE3
and so on for more and more template arguments. However, you can also split this into two macros: one that generates the typelist, and one to generate the specialization. I have done them, but believe me, not even I like it. It is not lack of preprocessing skill, I can tell you there is no satisfactory way to avoid the verbiage.