Postpone class template to its constructor

I'm afraid what I'm looking for is impossible. Perhaps this will change my design. I am looking to defer a template template to its constructor. Here is an example:

The following code works without problems:

#include <iostream>
using namespace std;

template<class T1,class T2>
T1 product(T1 t1,T2 t2)
{
    return (T1)(t1*t2);
}

int main()
{
    double t1=5.5;
    int t2=4;
    cout<<t1<<" x "<<t2<<" = "<<product(t1,t2)<<endl;
    return 0;
}

Now, if I want to wrap a function productinside a class:

#include <iostream>
using namespace std;

template<class T1,class T2>
class A
{
public:
    T1 num1;
    T2 num2;

    template<class T1,class T2>
    A(T1 t1,T2 t2)
    {
        num1=t1;
        num2=t2;
    }

    T1 product()
    {
        return (T1)(num1*num2);
    }

    T1 division()
    {
        return (T1)(num1/num2);
    }   
};

int main()
{
    double t1=5.5;
    int t2=4;

    // i need types here, this will not compile because 
    // i would need to explicitly state A<double, int> here.
    class A a(t1,t2);
    cout<<t1<<" x "<<t2<<" = "<<a.product(t1,t2)<<endl;
    return 0;
}

This code does not compile. Obviously, because it is looking <double,int>like a class template. Fixing a compiler error is easy, not my problem.

It bothers me that now I feel that I have lost my advantage! In the previous code, I could call the function without worrying about the type. I gave the arguments to the function. Now I must first give the parameter types to the first class. I cannot have a class defined from the automatic detection type t1 and t2. Is there a way to defer a template template to its constructor?

, , ! .

+4
1

-, " (tm)":

template<typename T1, typename T2>
auto make_A(T1 n1, T2 n2)->A<T1, T2> {
    return A<T1, T2>(n1, n2);
}

:

auto a = make_A(t1, t2);

. : auto - "" , , . , .

:

+6

All Articles