开发者

Tag-dispatch structure cannot insert object types

开发者 https://www.devze.com 2023-02-28 18:44 出处:网络
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.

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;};
0

精彩评论

暂无评论...
验证码 换一张
取 消