【问题标题】:Why does std::is_same give a different result for the two types?为什么 std::is_same 对这两种类型给出不同的结果?
【发布时间】:2018-11-25 02:23:33
【问题描述】:

在下面的代码中,为什么调用funfun(num)fun<const int>(num)这两种方式在编译时会给出不同的结果?

#include <iostream>
using namespace std;

template<typename T, typename = typename enable_if<!std::is_same<int, T>::value>::type>
void fun(T val)
{
    cout << val << endl;
}

int main(void)
{
    const int num = 42;
    fun(num);  //ERROR!

    fun<const int>(num);  //Right

    return 0;
}

【问题讨论】:

  • int prvalue 永远不会被 const 限定。

标签: c++ templates constants template-function template-argument-deduction


【解决方案1】:

参数声明为传值;然后在template argument deduction 中,忽略参数的顶级 const 限定符。

扣除开始前,对P和A进行如下调整 制作:

1) 如果 P 不是引用类型,

a) ...

b) ...

c) 否则,如果 A 是 cv 限定类型,则顶级 cv 限定符 扣分时忽略:

所以给定fun(num),模板参数T将推导出为int,而不是const int

如果您将参数更改为 pass-by-reference,const 部分将被保留。例如

template<typename T, typename = typename enable_if<!std::is_same<int, T>::value>::type>
void fun(T& val)

那么对于fun(num)T 将推导出为const int

【讨论】:

  • 而且num的类型是const intnum的值的类型就是int。没有 const int 类型的值(技术上的纯右值)这样的东西。
猜你喜欢
  • 1970-01-01
  • 2019-04-19
  • 2016-12-30
  • 1970-01-01
  • 2011-01-14
  • 2021-08-31
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
相关资源
最近更新 更多