小编Nic*_*227的帖子

为什么enable_if的模板构造函数中的可选参数可以帮助编译器推断模板参数?

最小的例子相当短:

\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

错误:没有匹配的函数可调用 \xe2\x80\x98Foo::Foo(std::array)\xe2\x80\x99

\n
\n

然而给出的解释

\n
\n

注意:模板参数推导/替换失败

\n
\n

没有帮助,正如std::enable_if<true, C>::type应该的C那样,两个构造函数中的第一个参数对于编译器来说应该看起来完全相同。我显然错过了一些东西。为什么编译器的行为不同?对于不使用可选参数的构造函数和enable_if,是否有其他解决方案?

\n

完整的错误消息:

\n
main.cpp:18:45: error: no matching function for call to …
Run Code Online (Sandbox Code Playgroud)

c++ templates enable-if

8
推荐指数
2
解决办法
603
查看次数

Entry::Occupied.get() 返回一个引用当前函数拥有的数据的值,即使 hashmap 应该拥有所有权

我的目标是在 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)

ownership rust

4
推荐指数
1
解决办法
539
查看次数

标签 统计

c++ ×1

enable-if ×1

ownership ×1

rust ×1

templates ×1