I took interest in C++ random number generation because of the concept of regular_invocable. To my understanding, regular_invocable is C++’s notion of a “pure function”, or something really close to it.
I was talking to ChatGPT about C++ concepts, and at some point asked this question:
“Does the compiler enforce regular_invocable? E.g. if I create a function that returns a random value, and then pass it to a template requiring a regular_invocable, would it cause a compilation error?”
ChatGPT incorrectly responded that the program below will fail to compile:
#include <concepts>
#include <iostream>
#include <random>
#include <functional> // Include this for std::invoke
// Example of a non-deterministic function
int random_func(int x) {
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<int> dis(1, 100);
return dis(gen); // Random value returned
}
template <std::regular_invocable<int> F>
void test(F&& f) {
std::cout << "Result: " << std::invoke(std::forward<F>(f), 10) << std::endl;
}
int main() {
// IVK -- the comments below, generated by ChatGPT, are NOT CORRECT --
// The following line will cause a compilation error
// because random_func is not deterministic (it produces a random number)
test(random_func); // Compilation error
}
In fact, it initially responded with an example that was missing an include and a few std:: snippets, but it was fixed when I complained.
This ChatGPT response is incorrect. In reality, that compiler does not check that the function in question is pure. At least in Visual std::regular_invocable is defined as an alias of std::invocable.
// C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.35.32215\include\concepts _EXPORT_STD template <class _FTy, class... _ArgTys> concept regular_invocable = invocable<_FTy, _ArgTys...>;
Interestingly, when I asked ChatGPT this question on its own, and not in the middle of a conversation, ChatGPT gave the correct answer. So did Claude, Perplexity and Gemini. There must have been something in the context of our conversation that threw it off.
Morals of the story:
- The compiler treats
regular_invocableas an alias ofinvocable, it does not perform any “purity” checks./li> - Generative AI may hallucinate even about such simple and well-defined subject.
