为什么 std::is_function<F> 在推导 F 时返回 false_type?

Why does std::is_function<F> return false_type when F is deduced?

本文关键字:返回 type false lt function std 为什么 gt is      更新时间:2023-10-16

给定以下代码,其中自动推导出类型Function,当我断言Function是否是使用 std::is_function<Function> 的函数时,我得到了意想不到的结果:

#include <iostream>
#include <iomanip>
#include <type_traits>
template <typename Function>
bool test_type(Function&& f)
{
    return std::is_function<Function>::value;  
}
template <typename Function>
bool test_decltype(Function&& f)
{
    return std::is_function<decltype(f)>::value;
}
int f()
{
    return 1;
}
int main()
{
    std::cout << std::boolalpha
        << "is_function<Function>:    " << test_type(f) << std::endl
        << "is_function<decltype(f)>: " << test_decltype(f) << std::endl
        << std::endl
        << "Explicit type:" << std::endl
        << "is_function<Function>:    " << test_type<int()>(f) << std::endl
        << "is_function<decltype(f)>: " << test_decltype<int()>(f) << std::endl;
    return 0;
}

然而,结果是(这里:http://ideone.com/Jy1sFA,使用 MSVC2013.4 在本地验证):

is_function<Function>:    false
is_function<decltype(f)>: false
Explicit type:
is_function<Function>:    true
is_function<decltype(f)>: false

我希望即使在推断的情况下is_function<Function>也会true_type。老实说,我什至希望is_function<decltype(f)>在这两种情况下都true_type,但唉,事实并非如此。

对于您的类型,您可以使用std::remove_reference的额外参考:

template <typename Function>
bool test_type(Function&& f)
{
    return std::is_function<typename std::remove_reference<Function>::type>::value;
}
template <typename Function>
bool test_decltype(Function&& f)
{
    return std::is_function<typename std::remove_reference<decltype(f)>::type>::value;
}

现场示例