【发布时间】:2021-02-20 15:25:05
【问题描述】:
std::invocable 和 std::regular_invocable 有什么区别?根据来自的描述
https://en.cppreference.com/w/cpp/concepts/invocable 我希望 std::regular_invocable 概念在调用时不允许更改函数对象的状态(或者至少调用的结果应该总是返回相同的结果)。
为什么下面的代码可以编译?
使用命令编译:g++-10 -std=c++2a ./main.cc。
#include <iostream>
#include <concepts>
using namespace std;
template<std::regular_invocable F>
auto call_with_regular_invocable_constraint(F& f){
return f();
}
template<std::invocable F>
auto call_with_invocable_constraint(F& f){
return f();
}
class adds_one {
int state{0};
public:
int operator()() {
state++;
return state;
}
};
int main()
{
auto immutable_function_object([]() { return 1; });
adds_one mutable_function_object;
// I would expect only first three will be compiled and the last one will fail to compile because the procedure is
// not regular (that is does not result in equal outputs given equal inputs).
cout << call_with_invocable_constraint(immutable_function_object) << endl;
cout << call_with_invocable_constraint(mutable_function_object) << endl;
cout << call_with_regular_invocable_constraint(immutable_function_object) << endl;
cout << call_with_regular_invocable_constraint(mutable_function_object) << endl; // Compiles!
}
程序的输出:
1
1
1
2
【问题讨论】:
-
auto mutable_fun = [n=0] () mutable { return n++; };这也适用于regular_invocable -
@pptaszni 它确实有效,但语义不正确。
标签: c++ generic-programming c++20