問題描述
如果我有一個模板函數,例如這樣:
If I have a template function, for example like this:
template<typename T>
void func(const std::vector<T>& v)
有什么方法可以在函數內確定 T 是否是指針,或者我必須為此使用另一個模板函數,即:
Is there any way I can determine within the function whether T is a pointer, or would I have to use another template function for this, ie:
template<typename T>
void func(const std::vector<T*>& v)
謝謝
推薦答案
確實,模板可以做到這一點,部分模板特化:
Indeed, templates can do that, with partial template specialization:
template<typename T>
struct is_pointer { static const bool value = false; };
template<typename T>
struct is_pointer<T*> { static const bool value = true; };
template<typename T>
void func(const std::vector<T>& v) {
std::cout << "is it a pointer? " << is_pointer<T>::value << std::endl;
}
如果在函數中你做的事情只對指針有效,你最好使用單獨函數的方法,因為編譯器對整個函數進行類型檢查.
If in the function you do things only valid to pointers, you better use the method of a separate function though, since the compiler type-checks the function as a whole.
但是,您應該為此使用 boost,它也包括:http://www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html
You should, however, use boost for this, it includes that too: http://www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html
這篇關于確定 Type 是否是模板函數中的指針的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!