gpt4 book ai didi

c++ - 无法实例化模板 : template arg deduction/substitution failed

转载 作者:行者123 更新时间:2023-11-30 03:25:36 32 4
gpt4 key购买 nike

以下程序(使用标准随机数引擎)给出“模板参数推导/替换失败”编译错误:

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)>();
^

为什么会这样?解决方案是什么?

最佳答案

首先, std::linear_congruential_engine 是一个类模板,你需要为它指定模板参数,例如linear_congruential_engine<std::uint_fast32_t, 16807, 0, 2147483647> .

linear_congruential_engine<std::uint_fast32_t, 16807, 0, 2147483647>指的是一种类型,typenamedecltype是不必要的。

例如,您可以更改

gener<typename decltype(linear_congruential_engine)>();

gener<linear_congruential_engine<std::uint_fast32_t, 16807, 0, 2147483647>>();

Live Sample

关于c++ - 无法实例化模板 : template arg deduction/substitution failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48944212/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com