首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自动模板推理中的一致性

自动模板推理中的一致性
EN

Stack Overflow用户
提问于 2019-12-18 17:58:15
回答 1查看 127关注 0票数 2

在下面的示例中,我希望行a.foo(j);将const限定符传递给模板化方法。

代码语言:javascript
复制
#include <iostream>
#include <type_traits>

struct A
{
    template<typename T>
    void foo(T i) const
    {
        std::cout << "Is const type: " << std::is_const<T>::value << "\n";
    }
};

int main() {

    A a;

    int i = 0;
    const int j = 0;

    a.foo(i);
    a.foo(j);

    a.foo<decltype(i)>(i);
    a.foo<decltype(j)>(j);

    a.foo<int>(i);
    a.foo<const int>(j);

    return 0;
}

然而,我从gcc和clang (c++17)获得的输出如下。

代码语言:javascript
复制
Is const type: 0
Is const type: 0
Is const type: 0
Is const type: 1
Is const type: 0
Is const type: 1

第二行为false,而不是true。那么为什么自动模板演绎会删除cv限定符呢?有什么具体的原因吗?

PS。上面的例子可以找到这里

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-18 18:16:20

T类型的扣减将始终是衰减的。int const的衰变类型只是intint[3]的腐朽类型是int*

问题是,这个代码是正确的。

是的,在foo内部,您永远无法更改j的值。在foo内部,您有一个副本,它由foo来决定它是否希望自己的参数在函数体中是常数的。

但是,还有其他形式的扣减必须维护const才能用参数调用。这不是您的代码的解决方案,而只是一个示例:

代码语言:javascript
复制
template<typename T>
void frob(T& i)
{
    std::cout << "Will it be const? " << std::is_const<T>::value << "\n";
}

auto main() -> int {
    int const myInt = 9;
    frob(myInt);
}

要被调用,参数必须是int const&,所以这就是将要推导的内容。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59397717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档