2016-12-06 102 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