【问题标题】:Why does std::is_function<F> return false_type when F is deduced?为什么推导 F 时 std::is_function<F> 返回 false_type ?
【发布时间】:2014-12-27 10:13:16
【问题描述】:

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

#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&lt;Function&gt;true_type 即使在推断的情况下。老实说,我什至期望is_function&lt;decltype(f)&gt; 在这两种情况下都是true_type,但可惜不是。

【问题讨论】:

  • 对函数的引用不是函数。这是一个参考。

标签: c++ templates typetraits type-deduction


【解决方案1】:

您可以使用您的类型的额外参考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;
}

Live example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多