考虑一个简单的函数模板:
template <typename T>
void FunctionTemplate(T t){
}
void MyFunction(){
int a;
FunctionTemplate(a);
FunctionTemplate<int>(a);
}
Run Code Online (Sandbox Code Playgroud)
在第一次调用(FunctionTemplate(a))时,编译器会解决引发问题的类型,是否有任何理由存在调用FunctionTemplate(FunctionTemplate<int>(a))的第二种方法或者我们无法使用第一种方法的任何令人信服的理由?
编辑:我的术语有点偏,所以请根据需要进行编辑.
Jos*_*eld 13
有时您会想要指定模板参数,即使您不需要.假设你的函数接受一个类型的参数,T你有一个int但是你希望函数把它作为一个float.然后你需要明确说出来FunctionTemplate<float>(my_int).
还有很多情况下无法推导出模板参数.考虑以下:
template <typename T>
T FunctionTemplate() {
return T();
}
Run Code Online (Sandbox Code Playgroud)
无论你怎么称呼它,如果你不提供模板参数,T就不能自动推导出类型.在这种情况下,简单的原因是调用站点没有说明它期望返回类型是什么.
对于术语:当您未指定模板参数时,隐式实例化模板; 当您指定模板参数时,将显式实例化模板.
假设您要将该函数作为参数传递给另一个方法;
myAlgorithm( myFunction<int> );
Run Code Online (Sandbox Code Playgroud)
或者假设您要保证函数的浮点版本用于速度;
myFunction<float>( 2.0 );
Run Code Online (Sandbox Code Playgroud)
(忘了写2.0f不是现在的问题)
用法是强制编译器使用特定版本的模板函数:
template <typename T>
T func(T x, T y)
{
// ...
}
int main()
{
int x = 10;
float y = 20;
func(x, y); //ERROR no matching function for call to 'func(int&, float&)'
func<float>(x, y); // OK, Uses float version of func
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
253 次 |
| 最近记录: |