省略 C++ 模板参数列表时的区别 [英] Difference when omitting the C++ template argument list
本文介绍了省略 C++ 模板参数列表时的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么时候可以省略 C++ 模板参数列表?例如在 Visual Studio 2010 中,这段代码编译得很好:
When can you omit the C++ template argument list? For example in Visual Studio 2010 this piece of code compiles fine:
template<class T>
Vec2<T> Vec2<T>::operator+ (const Vec2 &v) const
{
return Vec2(x + v.x, y + v.y);
}
如果你内联代码,它实际上是在没有任何参数列表的情况下编译的.但这真的和下面的版本一样吗?
If you inline the code, it actually compiles without any argument list. But is this really the same as the following version?
template<class T>
Vec2<T> Vec2<T>::operator+ (const Vec2<T> &v) const
{
return Vec2<T>(x + v.x, y + v.y);
}
推荐答案
在类中可以省略类类型的参数:
Inside a class you can omit the argument on the class type:
template<typename K>
struct A {
A<K> foo1; // legal
A foo2; // also legal and identical to A<K> foo
A bar(A x) {...} // same as A<K> bar(A<K> x) {...}
};
在类范围之外,您需要模板参数:
Outside of a class scope you need the template arguments:
// legal
template<typename K>
A<K> foo(A<K> x) { return A<K>(); }
// illegal!
template<typename K>
A foo(A x) { return A(); }
如果你在类外声明一个成员函数,你需要返回类型和类的模板列表:
If you declare a member function outside the class, you need the template list for the return type and for the class:
// legal
template<typename K>
A<K> A<K>::bar(A<K> x) { return A<K>(x); }
// legal
template<typename K>
A<K> A<K>::bar(A x) { return A(x); }
// illegal!
template<typename K>
A A::bar(A<K> x) { return A<K>(x); }
这篇关于省略 C++ 模板参数列表时的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文