I have a some libraries which have a lot of common classes but the namespaces are different. Most of the code I was writing could be easily reused by classes in both libraries so after some reading I tried a technique of using the templates to pass namespace. As you can see in the program below. However the issue is that not all classes are common so I create different templates to pass to Util. (templateNamespace and templateNamespaceb)
I was expecting that if I don't pass a type and not call a function it should not get generated and things should be fine. However it only works if the the type is not in the function signature. So for eg in the code below, namespace B does not have the type 'T2' and 'print2' in Util depends on T2. If I change print2 to 'void print2(typename schemans::T2 t2)' this program does not compile saying 'B' does not have T2 but if I declare it inside the function it compiles fine. could someone please explain the behaviour ? I hope I have explained it well if not let me know and i'll try again
#include <iostream>
namespace A
{
class T1{
public:
int i;
};
class T2{
public:
int x;
};
};
namespace B
{
class T1{
public:
int i;
};
};
template <typename schemans>
class util{
public:
void print(typename schemans::T1 tobj)
{
std::cout << tobj.i << std::endl;
}
void print2()
{
typename schemans::T2 t2;
t2.x = 13;
std::cout << t2.x << std::endl;
}
};
template <typename test, typename test2>
struct templateNamespace{
typedef test T1;
typedef test2 T2;
};
template <typename test>
struct templateNamespaceb{
typedef test T1;
};
int main(int agrc, char* argv[])
{
typedef templateNamespace<A::T1, A::T2> a_NS;
util<a_NS> utilObj;
A::T1 t1;
t1.i = 10;
A::T2 t2;
t2.x = 12;
utilObj.print(t1);
utilObj.print2();
typedef templateNamespaceb<B::T1> b_NS;
util<b_NS> utilObj2;
B::T1 t3;
t3.i = 11;
utilObj2.print(t3);
}