简体   繁体   English

实例化模板成员函数

[英]Instantiate a template member function

I have template member functions, but I cannot figure out how I can instantiate them when I am using them properly.我有模板成员函数,但是当我正确使用它们时,我无法弄清楚如何实例化它们。 The structure is as follows:结构如下:

// foo.h
class Foo {
template<typename T>
T Func(T);
}
#include "foo.tpp"
// foo.tpp
template<typename T>
T Func(T input) {return(input);}

How should I instantiate the template if I want to realize the following code in the main function?如果想在main函数中实现如下代码,应该如何实例化模板?

//main.cpp
#include "foo.h"
int main()
{
    Foo obj;
    int int_input, int_output;
    int_output = obj.Func(int_input);
    double double_input, double_output;
    double_output = obj.Func(double_input);
    return 0;
}

I have checked answers for similar questions such as Instantiation of template member function , but I do not want to instantiate all the member functions for all combinations every time I use them.我已经检查了类似问题的答案,例如模板成员函数的实例化,但我不想在每次使用它们时为所有组合实例化所有成员函数。 Another option might be defining the class as a template class and instantiate different classes using template class Foo<int>;另一种选择可能是将类定义为模板类并使用template class Foo<int>;实例化不同的类template class Foo<int>; . . However, this forces me to define different classes for different type of member functions, which I do not prefer.然而,这迫使我为不同类型的成员函数定义不同的类,这是我不喜欢的。 Is there other solution?还有其他解决方案吗? Thank you very much!非常感谢!

template<typename T>
T Func(T input) {return(input);}

This declares a free-standing function template in the global scope that is unrelated to your Foo class.这在全局范围内声明了一个与您的Foo类无关的独立函数模板。 To implement the member function, you need to prefix the function definition's name with Foo:: , as you would for any other member function implementation.要实现成员函数,您需要在函数定义的名称前加上Foo::前缀,就像任何其他成员函数实现一样。

template<typename T>
T Foo::Func(T input){ return input; }

Also note that return(value);还要注意return(value); as opposed to return value;return value;相反return value; is a slight anti-pattern.是一种轻微的反模式。 While this doesn't usually matter, it can make a difference when using things like the decltype(auto) inferred return type and cause an accidental dangling reference.虽然这通常无关紧要,但在使用诸如decltype(auto)推断返回类型之类的东西时可能会有所不同,并导致意外的悬空引用。

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

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