gpt4 book ai didi

c++ - 使用模板参数指定策略

转载 作者:行者123 更新时间:2023-12-02 10:17:23 25 4
gpt4 key购买 nike

我知道我们还可以传递模板参数来选择应执行的功能。我发现它们可以替代函数指针,因为函数指针具有运行时成本,而模板参数则没有。同样,模板参数可以内联,而函数指针则不能。

好吧,这就是我写的以描述我对此的理解。我接近了,但是在某处缺少一些细微的细节。

template<class T>
class String {
public:
T str;
String() { std::cout << "Ctor called" << std::endl; }
};

template<class T, class C>
int compare(const String<T> &str1,
const String<T> &str2) {
for (int i = 0; (i < str1.length()) && (i < str2.length()); ++i) {
if (C::eq(str1[i], str2[i])) {
return false;
}
}
return true;
}

template<class T>
class Cmp1 {
static int eq(T a, T b) { std::cout << "Cmp1 called" << std::endl; return a==b; }
};

template<class T>
class Cmp2 {
static int eq(T a, T b) { std::cout << "Cmp2 called" << std::endl; return a!=b; }
};

int main() {
String<std::string> s;
s.str = "Foo";
String<std::string> t;
t.str = "Foo";
compare<String<std::string>, Cmp1<std::string> >(s, t);
// compare(s, t);
}

代码详情:

我有一个String类,它带有一个参数并创建该类型的成员函数。
我有一个比较函数,它接受两个String&参数。比较函数传递给它。
Cmp1和Cmp2是两个比较功能。
compare<String<std::string>, Cmp1<std::string> >(s, t);

在这里无法编译。我尝试了其他方式打电话,但徒劳无功。

最佳答案

看起来您想要这样的东西:

#include <iostream>
#include <string>

template<class T>
class String {
public:
T str;
String() { std::cout << "Ctor called" << std::endl; }
};

template<class T, class C>
int compare(const String<T> &str1,
const String<T> &str2) {
for (int i = 0; (i < str1.str.length()) && (i < str2.str.length()); ++i) {
if (C::eq(str1.str[i], str2.str[i])) {
return false;
}
}
return true;
}

template<class T>
class Cmp1 {
public:
static int eq(T a, T b) { std::cout << "Cmp1 called" << std::endl; return a==b; }
};

template<class T>
class Cmp2 {
public:
static int eq(T a, T b) { std::cout << "Cmp2 called" << std::endl; return a!=b; }
};

int main() {
String<std::string> s;
s.str = "Foo";
String<std::string> t;
t.str = "Foo";
compare<std::string, Cmp1<char> >(s, t);
// compare(s, t);
}

code

说明:
您已经在 String的定义中有了 compare,您只需要发送 T即可。

相比之下,您正在尝试遍历整个 std::string,因此现在可以编译代码。

您在 std::string上调用了 cmp,实际上是 str[index],因此您需要使用 char模板参数来调用cmp。

关于c++ - 使用模板参数指定策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61462920/

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