【发布时间】:2020-02-24 04:50:39
【问题描述】:
我已将代码减少到以下最低代码:
#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),state_t前面没有const。似乎const 是从递归调用中推导出来的,因为actions 是tt 对象的const-ref 向量。我认为论证推论忽略了const?这怎么会发生?
【问题讨论】:
标签: c++ templates template-argument-deduction