以下程序(使用标准随机数引擎)给出"模板参数扣除/替换失败"编译错误:
http://coliru.stacked-crooked.com/a/e3c3ac933ed7b958
/// LCE1.cpp
///
/// Tests the linear congruential engine.
///
/// Dir: SW > Applications > Samples > C++Samples > Introductory > StdLib > Numerics > RandomNumbers > Engines > LCE > LCE1
///
#include <random> /// linear_congruential_engine
#include <iostream>
using namespace std;
/// Generate random numbers using the specified engine.
template<typename Eng>
void gener();
int main()
{
gener<typename decltype(linear_congruential_engine)>();
}
/// Generate random numbers using the specified engine.
template<typename Eng>
void gener()
{
/// Create an engine of the specified type.
Eng e;
/// Generate 500 random numbers.
for (int i = 0; i < 500; ++i)
e();
cout << "OK" << endl;
}
编译错误是:
g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In function 'int main()':
main.cpp:21:4: error: parse error in template argument list
gener<typename decltype(linear_congruential_engine)>();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:21:57: error: no matching function for call to 'gener<<expression error> >()'
gener<typename decltype(linear_congruential_engine)>();
^
main.cpp:16:6: note: candidate: template<class Eng> void gener()
void gener();
^~~~~
main.cpp:16:6: note: template argument deduction/substitution failed:
main.cpp:21:57: error: template argument 1 is invalid
gener<typename decltype(linear_congruential_engine)>();
^
为什么会这样?解决方案是什么?
答案 0 :(得分:2)
首先,std::linear_congruential_engine
是一个类模板,你需要为它指定模板参数,例如: linear_congruential_engine<std::uint_fast32_t, 16807, 0, 2147483647>
。
linear_congruential_engine<std::uint_fast32_t, 16807, 0, 2147483647>
是指类型,typename
和decltype
是不必要的。
例如,您可以更改
gener<typename decltype(linear_congruential_engine)>();
到
gener<linear_congruential_engine<std::uint_fast32_t, 16807, 0, 2147483647>>();