C++ 模板中 const int 和 int 的不同行为

问题描述 投票:0回答:1

当我使用 C++ 模板时,我发现有时它会给出不直接的结果。

#include <cstdlib>
#include <iostream>

template<class f0>
void func(const int& a1, f0& a2)
{
    std::cout << a1 + a2 << '\n';
    return;
}

template<class f0, class f1>
void func(f0& a1, f1& a2)
{
    std::cout << a1 - a2 << '\n';
    return;
}


int main(int argc, char *argv[])
{
    int bb = 3;
    int bbb = 3;
    func(static_cast<const int &>(bb), bbb); // 6
    func(bb, bbb); // 0
    func((int)bb, bbb); // 6
    
    func(static_cast<int &>(bb), bbb); // 0
    func(static_cast<int>(bb), bbb); // 6
    return 0;
}

当我将整数传递给第一个参数时,它被认为是与

const int &
的区别。然而,当我重新打包它到
int
时。我选择
const int&
的模板。

我找不到一个很好的解释来解释这种行为。有什么关于它如何工作的建议吗?

谢谢。

c++ templates static-cast
1个回答
0
投票

但是,当我将其重新打包为 int.我选择const int&的模板。

表达式

(int)bb
int 类型的
prvalue
(因此是 rvalue),并且由于右值不能绑定到对非常量 intlvalue 引用,因此第一个重载
void func(const int& a1, f0& a2)
是这里是唯一可行的选项。

打电话也一样

func(static_cast<int>(bb), bbb);

© www.soinside.com 2019 - 2024. All rights reserved.