下文所有语句的默认前提:
#include<bits/stdc++.h>
using namespace std;
我试图声明一个RNG,使用std::random_device类的实例的operator()
结果作为随机种子:
mt19937 rng(random_device()());
这条语句会CE,并且错误信息让人丈二和尚摸不着头脑。看起来是什么歧义导致的,然而我实在是想象不出来有什么歧义。
Clang++编译错误信息:
2.cpp:7:27: error: function cannot return function type 'std::random_device ()'
mt19937 rng(random_device()());
^
2.cpp:7:13: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
mt19937 rng(random_device()());
^~~~~~~~~~~~~~~~~~~
2.cpp:7:14: note: add a pair of parentheses to declare a variable
mt19937 rng(random_device()());
^
(
1 warning and 1 error generated.
我按照它说的加上一对多余的括号,就可以通过编译。此外,我还自己试验出来了其他几种魔改方法:
mt19937 rng((random_device()()));
mt19937 rng(random_device{}());
mt19937 rng{random_device()()};
auto v=random_device()();
mt19937 rng(v);
既然这些代码都能通过编译,为啥偏偏mt19937 rng(random_device()());
会有歧义呢?