gpt4 book ai didi

c++ - 如何在 C++ 中为多个类类型指定相同的模板化成员函数?

转载 作者:行者123 更新时间:2023-11-28 01:14:17 25 4
gpt4 key购买 nike

为了避免大量输入,我想为多个类定义一次函数。我希望模板系统能够为它们中的每一个提供定义。我想一个非平凡的宏也可以做到这一点,但它们似乎不太受欢迎。由于其复杂性,我不希望在可以为 S1、S2 创建基类的地方使用继承。

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();
}

但请注意:继承本身会带来一大堆问题,因此您是否真的想这样做还有待商榷。

关于c++ - 如何在 C++ 中为多个类类型指定相同的模板化成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59205201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com