定義一個函數和指向該函數的指針,然后判斷函數指針解引用之后是否為函數void test1() {}int main(){ void(*t1)() = test1; std::cout << std::is_function<decltype(*t1)>::value << std::endl; std::cout << std::is_function<decltype(test1)>::value << std::endl; std::cout << (typeid(decltype(test1)).hash_code() == typeid(decltype(*t1)).hash_code()) << std::endl;
return 0;
}最后輸出為:011直接比較*t1和test1的類型,結果表明類型一致,但第一個輸出為什么為0已知道使用函數名調用函數時會被轉化為函數函數指針想不明白這里為什么不對是模板匹配參數的規則造成的嗎?is_function的部分實現:template<typename> struct is_function
: public false_type { }; template<typename _Res, typename... _ArgTypes> struct is_function<_Res(_ArgTypes...)>
: public true_type { };
1 回答

慕慕森
TA貢獻1856條經驗 獲得超17個贊
decltype(*t1)的結果不是函數,而是函數引用,這是因為*t1返回一個lvalue,對于lvalue,decltype返回引用類型。
也就是說,不是
void()
而是
void (&) ()
由于是引用,is_function自然不能生效。使用remove_reference去除這個引用即可。
#include <iostream>#include <type_traits>#include <typeinfo>void test1() {}typedef void TEST();int main(){ TEST* t1 = test1; std::cout << std::is_reference<decltype(*t1)>::value << std::endl; //1 std::cout << std::is_function<std::remove_reference<decltype(*t1)>::type>::value << std::endl; // 1 return 0; }
- 1 回答
- 0 關注
- 535 瀏覽
添加回答
舉報
0/150
提交
取消