我向tag_dispatch名称空间上的eat函数发送了一个名为apple a("Apple")的对象实例。为什么eat函数不能被instants对象接受。
..\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 我从link编译的源代码在这里
发布于 2011-04-27 10:54:21
在代码中的任何位置都没有定义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;};https://stackoverflow.com/questions/5798683
复制相似问题