I am having a problem calling a template function with two template arguments.
I have a class and the class accepts objects of two different types. I don’t know the types yet, so I left them as template parameters. I then store the objects in wrapper classes. In the end I want to be able to call a templated function with two template arguments, that takes my two objects. But I am perplexed at how to do this.
Here is a stripped down version of the code to explain my problem.
template<typename A, typename B>
void someTemplateFunction(A a, B b);
class Problem
{
private:
class WrapperA
{
public:
virtual void doSomething() = 0;
};
template<typename A>
class ConcreteWrapperA : public wrapperA
{
private:
A a;
public:
ConcreteWrapperB(A b_) : a(a_) {}
virtual void doSomething();
};
class WrapperB
{
public:
virtual void doSomething() = 0;
};
template<typename B>
class ConcreteWrapperB : public wrapperB
{
private:
B b;
public:
ConcreteWrapperB(B b_) : b(b_) {}
virtual void doSomething();
};
WrapperA *a;
WrapperB *b;
public:
template<typename A>
void setA(A a)
{
a = new ConcreteWrapperA<A>(a);
}
template<typename B>
void setB(B b)
{
a = new ConcreteWrapperB<B>(b);
}
void call_someTemplateFunction(); // ??????? How do i do this?
};
The problem is that you’ve type-erased both types
AandBseparately, so there’s nowhere in the translation of your code that both typesAandBare known.If you can write a single function
template<typename A, typename B> void set(A, B)then you could capture the pair type<A, B>at that point.Alternatively, would it be possible for
someTemplateFunctionto operate without knowing both typesAandBat the same time?This is an issue fundamental to the design of C++ as a single-pass, separate compilation language.
Suppose that your program has three compilation units;
A.cppcallssetAwith a range of typesT[A],B.cppcallssetBwith another range of typesT[B], andC.cppowns theProblemobject and wants to callsomeTemplateFunction. Then there’s no time during compilation when the compiler knows both the range of types inA.cppand the range of types inB.cpp, so it can’t instantiatesomeTemplateFunctionwith the appropriate cross-productT[A] x T[B].