2011-07-07 17 views
6

我想寫一個函數,可以使用C++ 0x的type_traits功能處理char & wchar_t。是的,我知道如何在沒有type_traits的情況下做到這一點,但我希望使用type_traits來更好地理解該功能。是否可以使用type_traits區分char&wchar_t?

template <typename T> 
void SplitIt(T* base, T* ext, const std::basic_string<T>& fullFilePath, std::true_type) 
{ 
    _splitpath(fullFilePath.c_str(),NULL,NULL,base,ext); 
} 

template <typename T> 
void SplitIt(T* base, T* ext, const std::basic_string<T>& fullFilePath, std::false_type) 
{ 
    _wsplitpath(fullFilePath.c_str(),NULL,NULL,base,ext); 
} 

template <typename T> 
std::basic_string<T> GetBaseName(const std::basic_string<T>& fullFilePath) 
{ 
    T base[300], ext[50]; 

    SplitIt(base, ext, fullFilePath, /*What goes here?*/); 

    return std::basic_string<T>(buf) + ext; 
} 


int main() 
{ 
    std::basic_string<TCHAR> baseName = GetBaseName(std::basic_string<TCHAR>(__FILE__)); 
} 

是否有任何type_traits屬性區分char和wchar_t?

回答

7

我覺得有一個is_same屬性,因此

SplitIt(base, ext, fullFilePath, is_same<T, char>()); 

應該工作。

+0

Pff,簡單的解決方案! ...我很慚愧,甚至沒有想到... :( – Xeo

+0

輝煌!雖然它應該是is_same 在我的代碼。謝謝。 – Sharath

+0

@Sharat:對,修正它... – MartinStettner

1

AFAICS,在<type_traits>標題中沒有這樣的內容。然而,這是微不足道的自己做吧,你只需要切換過載,因爲下面的,現在產量爲wchar_tstd::false_typechar(和其他一切)和std::true_type

#include <type_traits> 

template<class T> 
struct is_wchar 
    : std::false_type 
{ 
}; 

template<> 
struct is_wchar<wchar_t> 
    : std::true_type 
{ 
}; 

// usage: 

SplitIt(base, ext, fullFilePath, is_wchar<T>()); 
+0

在''標頭中有'is_same'屬性,它實現了這種行爲...... – MartinStettner

+0

謝謝,這也不錯。 – Sharath