简体   繁体   English

C ++使用 <template> 在.h中

[英]C++ using <template> in .h

I want to create a function that is 我想创建一个函数

while t is template<typename T> 而t是template<typename T>

string myFunction(T t) {
    string str1;
    //some computation with t
    return str1();
}

So in my .h file, I do something like 所以在我的.h文件中,我做了类似

class myClass {
    private:
    //some variable
    public:
    string myFunction(T); 
}

and of course it gives an error saying "what is T?" 当然会给出一个错误,说“什么是T?”

What should I do to make myFunction able to take a T ? 我应该怎么做才能使myFunction可以取T

Make a member function template: 制作成员函数模板:

class Foo {
    template<typename T>
    string myFunction(T t)
    {
    }
};

or, make a class template: 或者,制作一个类模板:

template<typename T>
class Foo {
    string myFunction(T t)
    {
    }
};

Whatever makes sense for your case. 无论哪种情况都适合您的情况。 If you're defining the function outside of class, then: 如果要在类之外定义函数,则:

class Foo {
    template<typename T>
    string myFunction(T);
};

template<typename T>
string Foo::myFunction(T t)
{
}

for member function template, or 用于成员函数模板,或

template<typename T>
class Foo {
    string myFunction(T);
};

template<typename T>
string Foo<T>::myFunction(T t)
{
}

for class template. 用于课程模板。

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

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