2011-04-27 43 views
0

我發送一個對象實例名稱apple a("Apple")到tag_dispatch命名空間的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()': 

我被宣佈爲吃功能下表示:

#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編譯這裏

回答

1

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

Conrmier凡在我的例子定義你的代碼? – 2011-04-27 03:49:51

+0

正上方'template void eat(T const&fruit){...} – 2011-04-27 03:50:56