gpt4 book ai didi

c++ - 递归模板化函数无法分配给具有const限定类型 'state'的变量 'const tt &'

转载 作者:行者123 更新时间:2023-12-01 14:43:21 24 4
gpt4 key购买 nike

我已将代码缩减为以下最小代码:

#include<iostream>
#include<vector>

class tt
{
public:
bool player;
std::vector<tt> actions;
};

template<typename state_t>
int func(state_t &state, const bool is_max)
{
state.player = true;

const auto &actions = state.actions;
if(state.actions.size())
{
auto soln = func(actions[0], false);
}

return 0;
}

int main(int argc, char const *argv[])
{
tt root;
func(root, true);

return 0;
}

当我尝试编译此代码时,我得到
test.cpp:14:17: error: cannot assign to variable 'state' with const-qualified type 'const tt &'
state.player = true;
~~~~~~~~~~~~ ^
test.cpp:19:19: note: in instantiation of function template specialization 'func<const tt>' requested here
auto soln = func(actions[0], false);
^
test.cpp:28:4: note: in instantiation of function template specialization 'func<tt>' requested here
func(root, true);
^
test.cpp:12:19: note: variable 'state' declared const here
int func(state_t &state, const bool is_max)
~~~~~~~~~^~~~~
1 error generated.

它声称状态是 const tt &类型。模板化函数的签名为 int func(state_t &state, const bool is_max),在 const前面没有 state_t。看来 const是从递归调用中推导出来的,因为 actionstt对象的const-ref vector 。我以为参数推导会忽略 const吗?怎么会这样呢?

最佳答案

答案主要摘自Scott Mayers Effective C++书。

template<typename T>
void f(ParamType param);
f(expr); // deduce T and ParamType from expr

ParamType是引用或指针,但不是通用引用

最简单的情况是ParamType是引用类型或指针类型,而不是通用引用。在这种情况下,类型推导的工作方式如下:
  • 如果expr的类型是引用,请忽略引用部分。
  • 然后将expr的类型与ParamType进行模式匹配以确定T。

  • 在参数推导过程中,它将忽略引用部分,而不是 const部分。

    在您的情况下,它是 const auto &actions = state.actions;,这意味着,对于 auto soln = func(actions[0], false);的模板参数推导,仅删除引用部分,而不删除cv限定词。

    书中的其他示例。
    template<typename T>
    void f(T& param); // param is a reference

    我们有这些变量声明,
    int x = 27;             // x is an int
    const int cx = x; // cx is a const int
    const int& rx = x; // rx is a reference to x as a const int
    the deduced types for param and T in various calls are as follows:

    f(x); // T is int, param's type is int&

    f(cx); // T is const int,
    // param's type is const int&

    f(rx); // T is const int,
    // param's type is const int&

    关于c++ - 递归模板化函数无法分配给具有const限定类型 'state'的变量 'const tt &',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60369740/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com