标记分派结构不能插入对象类型

Tag-dispatch structure cannot insert object types

本文关键字:插入 对象 类型 不能 结构 分派      更新时间:2023-10-16

我将对象实例名称apple a("Apple")发送给tag_dispatch名称空间上的eat函数。为什么eat函数不能被即时对象接受。

..tag_dispatch.hpp: In function 'void eat(const T&)':
..tag_dispatch.hpp:52: error: template argument 1 is invalid
..tag_dispatch.hpp:52: error: invalid type in declaration before '(' token
..tag_dispatch.hpp:52: error: invalid use of qualified-name '::apply'
..mem_define.cpp: In function 'int main()':

我被声明为一个eat函数,表示如下:

#ifndef TAG_DISPATCH_H
#define TAG_DISPATCH_H
struct apple_tag{};
struct banana_tag{};
struct orange_tag{};
struct apple
{
double reduis;
std::string name;
apple(std::string const& n): name(n){}
};
struct banana
{
double length;
std::string name;
banana(std::string const& n): name(n){}
};
namespace dispatch{
template <typename Tag> struct eat{};
template<>struct eat<apple_tag>
{
static void apply(apple const& a){
std::cout<<"Apple tag"<<std::endl;
}
};
template<>struct eat<banana_tag>
{
static void apply(banana const& b){
std::cout<<"Banana tag"<<std::endl;
}
};
}
template <typename T>
void eat(T const& fruit)
{
    dispatch::eat<typename tag<T>::type>::apply(fruit);
}
#endif 

我的源代码编译链接在这里

tag模板类在代码中的任何地方都没有定义。在使用tag<T>::type之前,必须先定义tag模板类。

您必须为每个标记的类型提供tag模板的专门化:

template <typename T>
struct tag {};
template <>
struct tag<apple> {typedef apple_tag type;};
template <>
struct tag<banana> {typedef banana_tag type;};