标记分派结构不能插入对象类型
Tag-dispatch structure cannot insert object types
我将对象实例名称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;};
相关文章:
- 将包含不可复制对象的对插入到映射中
- 在 std::map 中插入对象时构造函数中变量的地址
- 在 c++ 列表中插入对象
- 在列表C 中插入对象
- 如何创建插入对象使用duktape
- 如何在地图中插入对象以保持其排序
- bad_alloc通过右值和对象有效性插入对象时
- 插入对象以设置c++
- 在地图中插入对象而不复制对象
- C++:使用递归在二叉搜索树中插入对象
- 如何在矢量中高效、正确地插入对象
- vector插入对象的副本或引用
- 我可以插入对象到tr1 unordered_map
- 在ostreams中插入对象
- 如何在指针数组中插入对象
- 在链表中按升序插入对象
- 标记分派结构不能插入对象类型
- 链表-插入对象
- 在vector的下标处插入对象
- 按字母顺序向vector插入对象