[英]Templates in C++ / reference
现在是凌晨 3:30,我正在做一个关于 C++ 模板的练习。 我不明白在这种情况下我做错了什么,你能帮我理解吗? (我不太擅长 C++,两周前开始学习)。
这是主题:
[...],您必须编写函数模板 foreach 。 此函数允许通过为该数组的每个元素调用一个函数来浏览数组。 该函数接受数组开头的地址、函数的引用和数组的大小作为参数。 对函数的引用对应于以下原型: void func(const type& elem); 此外,您必须提供传递给函数 foreach 并显示每个元素的函数 print,每行一个,无论它们的类型如何。
这是我的代码:
#ifndef __EX03_H_INCLUDED__
# define __EX03_H_INCLUDED__
#include <iostream>
#include <iomanip>
template<typename type>
void foreach(type tab[0], (*)(print(const type& elem)), type size)
{
int i;
for (i = 0; i != size; i++)
print(tab[i]);
}
template<typename type>
void print(const type& elem)
{
std::cout << elem << std::endl;
}
#endif /* !__EX03_H__ */
和:
#include "ex03.hpp"
int main(void)
{
int tab[] = { 11, 3, 89, 42 };
foreach(tab, print<int>, 4);
std::string tab2[] = { "j’", "aime", "les", "templates", "!" };
foreach(tab2, print, 5);
return 0;
}
我只允许上交ex03.hpp,这只是一个测试主。 我想了解我做错了什么。 谢谢!
问题出在 foreach 模板化函数中:
固定的 ex03.hpp 看起来像这样:
#ifndef __EX03_H_INCLUDED__
#define __EX03_H_INCLUDED__
#include <iostream>
// option 1
template<typename T1, typename T2>
void foreach(T1* arr, void (*fnc)(const T1&), T2 size) {
for (T2 i = 0; i < size; i++) {
(*fnc)(arr[i]);
}
}
// option 2
template<typename T1, typename T2>
void foreach(T1 arr[], void (&fnc)(const T1&), T2 size) {
for (T2 i = 0; i < size; i++) {
(*fnc)(arr[i]);
}
}
template<typename T1>
void print(const T1& element) {
std::cout << element << std::endl;
}
#endif /* !__EX03_H__ */
和 main.cpp:
#include "ex03.hpp"
#include <string>
int main() {
const size_t tab1Size = 4;
int tab1[tab1Size] = { 11, 3, 89, 42 };
foreach(tab1, print, tab1Size);
const size_t tab2Size = 5;
std::string tab2[tab2Size] = { "j’", "aime", "les", "templates", "!" };
foreach(tab2, print, tab2Size);
return 0;
}
但我同意之前其他人所说的,你应该先学习 C++ 的基础知识,这样才能更容易理解更复杂的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.