2016-12-06 99 views
1

如果我有一個模板類如果模板arg是函數指針

template <class T> 
class foo 
{ /**/ } 

我怎麼會發現,如果T是一個函數指針?

std::is_pointerstd::is_function但沒有is_function_pointer

回答

4

只是刪除指針並檢查結果是一個函數。

下面是代碼示例:

#include <utility> 
#include <iostream> 


template<class T> constexpr bool foo() { 
    using T2 = std::remove_pointer_t<T>; 
    return std::is_function<T2>::value; 
} 


int main() { 
    std::cout << "Is function? " << foo<void (int)>() 
       << "; is function pointer? " << foo<int (*)()>() << "\n"; 

} 
+0

是函數指針解除引用相同的方式,在正常指針? 'int(* f)()'被引用爲'* f()'? – WARhead

+0

@Warhead,不要解除引用。如上所示使用'remove_pointer_t'。 – SergeyA

+0

好吧。我將使用'remove_pointer_t' – WARhead