[英]How do I use a templated class as an argument type?
I am new to C++ and I know this is very basic, but I couldn't determine the correct keywords to find a solution to this particular problem I'm having.我是 C++ 的新手,我知道这是非常基本的,但我无法确定正确的关键字来找到解决我遇到的这个特定问题的方法。
So say I have two classes: Food and Dog.所以说我有两个课程:食物和狗。 Food is a template class.
食物是一个模板 class。 I then want to pass a food object as an argument into a function called "eat" in Dog.
然后我想将食物 object 作为参数传递给在 Dog 中称为“吃”的 function。 What is the best way of doing this?
这样做的最佳方法是什么? Here is what I assumed would make the most sense, but it doesn't work.
这是我认为最有意义的,但它不起作用。
// main.cpp
#include <iostream>
#include "food.h"
#include "food.cpp"
#include "dog.h"
int main(void)
{
Food<int> *food = new Food(10);
Dog *dog = new Dog();
dog->eat(food);
delete food;
delete dog;
return 0;
}
// dog.h
#pragma once
class Dog()
{
public:
Dog();
~Dog();
void eat(Food<T>);
};
// dog.cpp
#include "dog.h"
Dog() {}
~Dog() {}
void eat(Food<T> food)
{
std::cout << "Eating food\n";
}
// food.h
#pragma once
template <class T>
class Food
{
public:
Food(T value);
~Food();
T value = -1;
};
// food.cpp
#include "food.h"
template <class T>
Food<T>::Food(T value): value(value) {}
template <class T>
Food<T>::~Food() {}
Does Dog also need to be made a template class just to pass in a template object to a single fucntion? Dog 是否还需要制作模板 class 才能将模板 object 传递给单个功能? That seems like a very convoluted way of doing it if there are 20 functions in a class, only one of which takes an argument that is templated, so I thought there might be a better alternative.
如果 class 中有 20 个函数,其中只有一个函数采用模板化的参数,那么这似乎是一种非常复杂的方法,所以我认为可能有更好的选择。
You don't need to make the whole class dog
template, you might just have template method:您不需要制作整个 class
dog
模板,您可能只有模板方法:
template <class T>
class Food
{
public:
Food(T value) : value(value) {}
T value;
};
class Dog
{
public:
template <typename T>
void eat(Food<T>) { std::cout << "Eating food\n"; }
};
int main()
{
Food<int> food(10);
Dog dog;
dog.eat(food);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.