<分区>
我希望开始在我的 C++ 类代码中放入模板,但我遇到了一种我以前从未经历过的情况。基本上我有一个非模板类,但我需要模板化的类中只有 1 个函数。
class example
{
public:
example();
~example();
<template T> templatefunction(T);
nontemplatefunction(string x);
};
这可能吗?如果是这样,这是一个常见的解决方案还是我完全错误地查看模板?
<分区>
我希望开始在我的 C++ 类代码中放入模板,但我遇到了一种我以前从未经历过的情况。基本上我有一个非模板类,但我需要模板化的类中只有 1 个函数。
class example
{
public:
example();
~example();
<template T> templatefunction(T);
nontemplatefunction(string x);
};
这可能吗?如果是这样,这是一个常见的解决方案还是我完全错误地查看模板?
最佳答案
正如人们在评论中指出的那样,这样做没有问题。
需要注意的一个方面是将方法 templatefunction
的定义放在哪里。目前(参见 ISO cpp FAQ ),您应该考虑将它放在头文件中,这与您可能对其他方法的定义所做的不同。因此,您将拥有 example.hpp
:
class example
{
public:
example();
~example();
template<typename T> void templatefunction(T);
void nontemplatefunction(string x);
};
template<typename T> void example::templatefunction(T)
{
}
然后是example.cpp
:
example::example(){}
void example::nontemplatefunction(string x)
{
}
关于非模板类中的 C++ 模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35356107/