求教一个模板类型推导的问题

2019-01-31 08:32:20 +08:00
 crayontxx
#include <stdio.h>
#include <type_traits>

enum class E : int
{
    A
};

template<typename T>
void Test(T&& t)
{
    if (std::is_enum<T>::value)
        printf("YES\n");
    else
        printf("NO\n");
}

template<typename T>
void Test2(T&& t)
{
    Test(t);
}

int main() {
    Test(E::A);
    Test2(E::A);
    return 0;
}

为什么输出结果是:

YES
NO

环境 g++ 7.3.0

2035 次点击
所在节点    C
6 条回复
AngelCriss
2019-01-31 08:50:19 +08:00
第二个应该 decay 成 int 了
a41050447
2019-01-31 09:17:12 +08:00
test2 传给 test 的是引用,
std::is_reference<T>
加个 std::move
lniwn
2019-01-31 09:20:11 +08:00
这就是 forward 存在的意义
crayontxx
2019-01-31 09:56:15 +08:00
感谢各位。
aqtata
2019-01-31 09:56:55 +08:00
退 c++保平安。

template<typename T>
void Test2(T&& t)
{
Test(std::forward<T>(t));
}
wutiantong
2019-01-31 14:03:59 +08:00
把 Test 的参数改成 const T &可能更符合你的代码意图

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/532027

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX