省略C ++模板参数列表时的差异 [英] Difference when omitting the C++ template argument list

查看:124
本文介绍了省略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);
}


推荐答案

类类型的参数:

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屋!

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