Tag-dispatch structure cannot insert object types
I send an object instants name apple a("Apple")
to an eat function on a tag_dispatch namespaces. Why an eat function cannot accepted by instants objects.
..\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()':
I was declared an eat functions represent below:
#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 ea开发者_开发百科t<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
My source code for compiling from link here
The tag
template class is not defined anywhere in your code. The tag
template class must be defined before you attempt to use tag<T>::type
.
You must provide specializations of the tag
template for each of your tagged types:
template <typename T>
struct tag {};
template <>
struct tag<apple> {typedef apple_tag type;};
template <>
struct tag<banana> {typedef banana_tag type;};
精彩评论