最小的例子相当短:
\n#include <iostream>\n#include <array>\n#include <type_traits>\n\nstruct Foo{\n //template <class C>\n //Foo(C col, typename std::enable_if<true,C>::type* = 0){\n // std::cout << "optional argument constructor works" << std::endl;\n //}\n template <class C>\n Foo(typename std::enable_if<true, C>::type col){\n std::cout << "no optional argument constructor works NOT" << std::endl;\n }\n};\n\nint main()\n{\n auto foo = Foo(std::array<bool,3>{0,0,1});\n}\n
Run Code Online (Sandbox Code Playgroud)\n第一个构造函数按预期工作。但是第二个构造函数无法编译,我得到
\n\n\n错误:没有匹配的函数可调用 \xe2\x80\x98Foo::Foo(std::array)\xe2\x80\x99
\n
然而给出的解释
\n\n\n注意:模板参数推导/替换失败
\n
没有帮助,正如std::enable_if<true, C>::type
应该的C
那样,两个构造函数中的第一个参数对于编译器来说应该看起来完全相同。我显然错过了一些东西。为什么编译器的行为不同?对于不使用可选参数的构造函数和enable_if,是否有其他解决方案?
完整的错误消息:
\nmain.cpp:18:45: error: no matching function for call to …
Run Code Online (Sandbox Code Playgroud) 我的目标是在 rust 书第 13.1 章的cacher 结构上实现建议的改进,即创建一个结构,它接受一个函数并使用记忆来减少给定函数的调用次数。为此,我创建了一个带有HashMap的结构
struct Cacher<T, U, V>
where T: Fn(&U) -> V, U: Eq + Hash
{
calculation: T,
map: HashMap<U,V>,
}
Run Code Online (Sandbox Code Playgroud)
和两种方法,一种构造函数和一种负责记忆的方法。
impl<T, U, V> Cacher<T, U, V>
where T: Fn(&U) -> V, U: Eq + Hash
{
fn new(calculation: T) -> Cacher<T,U,V> {
Cacher {
calculation,
map: HashMap::new(),
}
}
fn value(&mut self, arg: U) -> &V {
match self.map.entry(arg){
Entry::Occupied(occEntry) => occEntry.get(),
Entry::Vacant(vacEntry) => {
let argRef = vacEntry.key();
let …
Run Code Online (Sandbox Code Playgroud)