如何在 C++ 中为多个 class 类型指定相同的模板化成员函数?
How to specify the same templated member function for multiple class types in c++?
为了避免大量输入,我想为多个 classes 定义一次函数。我希望模板系统能够为它们中的每一个提供定义。我想一个非平凡的宏也可以做到这一点,但它们似乎不太受欢迎。由于其复杂性,我不想在可以为 S1、S2 创建基础 class 的地方使用继承。
struct S1 {
bool print(int i);
};
struct S2 {
bool print(int i);
};
// bool S1::print(int i) { i=+1; std::cout<<i; return true; } NOTE: this is the line I don't want to type many times for each S*
template< typename T >
bool T::print(int i) { i=+1; std::cout<<i; return true; } // TODO
int main() {
S1 s1 {};
s1.print( 5 );
}
你不能使用模板来"inject"一个自由函数成为多个独立类中每一个的成员函数。抱歉,事情不是这样运作的。
如果你非常想这样做,你可以通过继承来做到这一点:
#include <iostream>
struct Base {
public:
bool print() {
std::cout << "Printing something\n";
return true;
}
};
struct S1 : Base { };
struct S2 : Base { };
int main() {
S1 s1;
s1.print();
S2 s2;
s2.print();
}
但请注意:继承本身会带来一大堆问题,因此您是否真的想这样做还有待商榷。
这样的事情怎么样?
struct function
{
bool print(int i);
}
struct s1: public function
{
}
现在您可以使用 s1 的打印功能了。
为了避免大量输入,我想为多个 classes 定义一次函数。我希望模板系统能够为它们中的每一个提供定义。我想一个非平凡的宏也可以做到这一点,但它们似乎不太受欢迎。由于其复杂性,我不想在可以为 S1、S2 创建基础 class 的地方使用继承。
struct S1 {
bool print(int i);
};
struct S2 {
bool print(int i);
};
// bool S1::print(int i) { i=+1; std::cout<<i; return true; } NOTE: this is the line I don't want to type many times for each S*
template< typename T >
bool T::print(int i) { i=+1; std::cout<<i; return true; } // TODO
int main() {
S1 s1 {};
s1.print( 5 );
}
你不能使用模板来"inject"一个自由函数成为多个独立类中每一个的成员函数。抱歉,事情不是这样运作的。
如果你非常想这样做,你可以通过继承来做到这一点:
#include <iostream>
struct Base {
public:
bool print() {
std::cout << "Printing something\n";
return true;
}
};
struct S1 : Base { };
struct S2 : Base { };
int main() {
S1 s1;
s1.print();
S2 s2;
s2.print();
}
但请注意:继承本身会带来一大堆问题,因此您是否真的想这样做还有待商榷。
这样的事情怎么样?
struct function
{
bool print(int i);
}
struct s1: public function
{
}
现在您可以使用 s1 的打印功能了。