首页 > 解决方案 > C++:MSVC 错误 C2668:模版重载模棱两可,适用于 GCC 和 CLang

问题描述

我在此代码上收到 MSVC C2668 错误:

#include <vector>
#include <functional>

class A {
public:
    class B {
    public:
        bool isValid() const {return true;}
        void foo() const {};
    };
    std::vector<B> container;
};

template <class T>
inline void myForEach(const T &m, std::function<void (const typename T::B &)> action) {
    for(auto b : m.container)
        if(b.isValid())
            action(b);
}

template <class T>
inline void myForEach(T &m, std::function<void (typename T::B &)> action) {
    for(auto b : m.container)
        if(b.isValid())
            action(b);
}

void bar(const A& obj) {
    myForEach(obj, [&](const A::B& b){
        b.foo();
    });
}

int main(int, char *[]) {
    A obj;
    bar(obj);
    return 0;
}

似乎 MSVC 无法消除 A 对象的常量性:

note: may be 'void myForEach<const A>(T &,std::function<void (A::B &)>)'
        with
        [
            T=const A
        ]
note: or 'void myForEach<A>(const T &,std::function<void (const A::B &)>)'
        with
        [
            T=A
        ]

这段代码中有什么不能消除歧义的吗?我该怎么做才能使其具有适当的 const 正确性?GCC 和 CLang 构建没有错误。我正在使用 VS 2019、v16.7.3 和 MSVC 16.6.30225.117。

标签: c++c++11templates

解决方案


推荐阅读