2010-10-02 91 views
1

是否有可能返回一個對象的類型?例如,我想有構造是這樣的:返回一種物體的類型;

//pseudocode 
    template<class T> 
    void f(int value) 
    { 
    //depends on type T different action can be taken 
    } 

template<class T> 
type getType(T obj) 
{ 
return (type of obj); 
} 

,然後在主:

f<getType(Object)>(value); 

回答

5

是在某種意義上說,但您需要將T轉換爲參數。這是Eric Niebler探索的條件竅門,並解釋here

template<typename T> 
struct id { typedef T type; }; 

template<typename T> 
id<T> make_id(T) { return id<T>(); } 

struct get_type { 
    template<typename T> 
    operator id<T>() { return id<T>(); } 
}; 

#define pass_type(E) (true ? get_type() : make_id((E))) 

pass_type(expression)產生一個id<T>對象,使得T是CV-不合格類型表達的。所以你可以做

template<class T> 
void f(int value, id<T>) 
{ 
    // Now go on as usual on T 
} 

f(value, pass_type(Object)); 
+0

這真棒。 – GManNickG 2010-10-02 18:08:23

0

C++ 0x中有decltype和經銷商可以使用

0

在模板元編程中,這通常是通過類模板完成的。

template <typename T> 
struct GetType 
{ 
    typedef T type; // usually it's something more complex 
}; 

// example: partial specialization is used to compute element type of some container template 
template <typename T> 
struct GetType< MyContainerType<T> > 
{ 
    typedef T type; 
}; 


......................... 

// and now you use it: 
f<GetType<Object>::type>(value); 

這裏,struct GetType<T>可以被認爲是作爲(甲基)函數服用一種類型的參數並返回一個類型值。

0

我認爲你只需要使用函數模板專業化:

template<> 
void f(int value) 
{ 
    .. operations when an int 
} 


template<> 
void f(char value) 
{ 
    .. operations when a char 
} 


template<> 
void f(double value) 
{ 
    .. operations when a double 
} 


template<class T> 
void f(T value) 
{ 
    .. operations when a T (not int, char or double) 
} 
+0

我認爲就是這樣。我會明天檢查一下,然後讓你知道。感謝您的回答。 – 2010-10-02 18:35:42

+0

它與函數超載有什麼不同? – atzz 2010-10-03 08:50:34

+0

由於它是一個簡單的函數,我想它並沒有真正的不同,所以只需要函數重載就足夠了,但最終的所有模板仍然是必需的。 – JBRWilkinson 2010-10-03 20:25:31