模板功能调用 [英] Template Function Call

查看:63
本文介绍了模板功能调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板类和一个与模板类实例一起使用的模板函数:

I have a template class and a template function that works with instances of the template class:

template <class t> class calc
{
public:
    T el;
    calc(T t);
.............
};
template<class t> calc<t>::calc(T t){el=t;}





template<class tt1, class tt2> double the_sum(calc<int> &a,calc<double> &b)
{
    return a.el+b.el; 
}


void main()
{
        calc<int> C(10);
	calc<double> D(5.2);
	cout<<the_sum(C,D);/*->this is where I get  2 errors:
	1	error C2783: 'double the_sum(calc<t>,calc<double>)' : could not deduce template argument for 'TT1'	
	2	error C2783: 'double the_sum(calc<t>,calc<double>)' : could not deduce template argument for 'TT2'	
*/	


}


我的函数有什么问题,以及如何在主程序中调用函数"the_sum"以获取预期的答案.有可能吗?


What is wrong with my function and how shoul I call the function "the_sum" in the main program, to get the expected answer. is it possible?
Thanks in advance!

推荐答案

编译器不知道对tt1和tt2使用哪种类型进行实例化,因此不显示消息.

The compiler doesn''t know what type to use for tt1 and tt2 for instanciation therefore the message.

template <class tt1, class tt2> double the_sum(tt1& a,tt2& b)
{
 return (double)(a.el+b.el);
}


在这种情况下,编译器可以实例化隐式类型calc<int>calc<double>的模板函数. 问候,这也许看起来更好.


In this case the compiler can instanciate the template function for the types calc<int> and calc<double> implicit.
This maybe look better, regards.


根据我的理解,这就是我想出的-
Based on what I understand, this is what I''ve come up with -
template <class T>
class calc
{
public:
    T el;
    calc(T t);
};

template<class T>
calc<T>::calc(T t)
{
    el = t;
}

double the_sum(calc<int> &a, calc<double> &b)
{
    return a.el + b.el;
}


template <class T = double>   // default to type double
class calc
{
public:
    T el;
    calc(T t);
};

template<class T>
calc<T>::calc(T t)
{
    el = t;
}

// By using a more precise type as the argument, the compiler can verify that
// the function is called on an object of type calc<T>.

// Here const is not strictly required... but since the value is not modified
// it make sence to do so and it will allows const & objects to be passed.

template <class R, class S> double the_sum(calc<R> const &a, calc<S> const & b)
{
    return a.el + b.el;
}

int main()
{
    calc<int> c(2);
    calc<> d(2.3);    // double can be ommited here since default
    the_sum(c, d);

    return 0;
}



该代码已在Visual C ++ 2010中进行了测试.



This code was tested in Visual C++ 2010.


这篇关于模板功能调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆