简体   繁体   English

做模板 <typename T> 每个模板函数需要声明吗?

[英]Does template <typename T> need to be declared for each template function?

For a class with multiple template functions does template have to be included in each declaration like so: 对于具有多个模板功能的类,模板必须包含在每个声明中,如下所示:

class Foo
{
    public:
        template <typename T>
        void foo(T a);

        template <typename T>
        void bar(T b);
}

Or can you just include template <typename T> for the first declaration like so: 或者您可以只为第一个声明包括template <typename T> ,如下所示:

class Foo
{
    public:
        template <typename T>
        void foo(T a);
        void bar(T b);
}

I suspect only the first one is valid since without the ; 我怀疑只有第一个有效,因为没有; it makes me think the declaration is actually template <typename T> void foo(T a) if written on one line. 它使我认为声明如果实际上写在一行上,则实际上是template <typename T> void foo(T a) I assume its just convention to separate it into two lines! 我假设将其分为两行只是其惯例! Looking for confirmation. 寻找确认。

The template specifier must appear before each templated function. template说明符必须出现在每个模板函数之前。 Your second example will cause an error that T is not a recognized type for bar , since template <typename T> applies only to foo in this case. 您的第二个示例将导致一个错误,即T不是bar的公认类型,因为在这种情况下, template <typename T>仅适用于foo

Alternatively, if you wanted to use the same type for each function in a class, you could declare the entire class as a template: 另外,如果您想对一个类中的每个函数使用相同的类型,则可以将整个类声明为模板:

template <typename T>
class Foo
{
public:
    void foo(T a);
    void bar(T b);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM