我試圖寫出與overload
結構相同的代碼http://en.cppreference.com/w/cpp/utility/variant/visit,並將其擴展爲使用函數。函子基類的模糊過載
這裏是低於
#include <utility>
#include <type_traits>
#include <cassert>
#include <string>
namespace {
template <typename Func>
class OverloadFuncImpl : public Func {
public:
template <typename F>
explicit OverloadFuncImpl(F&& f) : Func{std::forward<F>(f)} {}
using Func::operator();
};
template <typename ReturnType, typename... Args>
class OverloadFuncImpl<ReturnType (*) (Args...)> {
public:
template <typename F>
explicit OverloadFuncImpl(F&& f) : func{std::forward<F>(f)} {}
ReturnType operator()(Args... args) {
return this->func(args...);
}
private:
ReturnType (*func) (Args...);
};
template <typename... Funcs>
class Overload;
template <typename Func, typename... Funcs>
class Overload<Func, Funcs...>
: public OverloadFuncImpl<Func>,
public Overload<Funcs...> {
public:
template <typename F, typename... Fs>
explicit Overload(F&& f, Fs&&... fs)
: OverloadFuncImpl<Func>{std::forward<F>(f)},
Overload<Funcs...>{std::forward<Fs>(fs)...} {}
using OverloadFuncImpl<Func>::operator();
using Overload<Funcs...>::operator();
};
template <typename Func>
class Overload<Func> : public OverloadFuncImpl<Func> {
public:
template <typename F>
explicit Overload(F&& f) : OverloadFuncImpl<Func>{std::forward<F>(f)} {}
using OverloadFuncImpl<Func>::operator();
};
}
template <typename... Funcs>
auto make_overload(Funcs&&... funcs) {
return Overload<std::decay_t<Funcs>...>{std::forward<Funcs>(funcs)...};
}
char foo(char ch) {
return ch;
}
int main() {
auto overloaded = make_overload(
[&](int integer) { return integer; },
[&](std::string str) { return str; },
[&](double d) { return d; },
foo);
assert(overloaded("something") == "something");
assert(overloaded(1.1) == 1.1);
return 0;
}
此轉載代碼https://wandbox.org/permlink/5Z2jsEjOewkGoPeX的錯誤,我得到
In file included from /opt/wandbox/gcc-7.2.0/include/c++/7.2.0/cassert:44:0,
from prog.cc:3:
prog.cc: In function 'int main()':
prog.cc:66:26: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
assert(overloaded(1.1) == 1.1);
^
prog.cc:62:21: note: candidate 1: main()::<lambda(double)>
[&](double d) { return d; },
^
prog.cc:19:20: note: candidate 2: ReturnType {anonymous}::OverloadFuncImpl<ReturnType (*)(Args ...)>::operator()(Args ...) [with ReturnType = char; Args = {char}]
ReturnType operator()(Args... args) {
^~~~~~~~
有幾個問題與編譯器和標準的解釋,使人們有必要進口的operator()
一個一個。但不知何故OverloadFuncImpl
函數專門化的operator()
好像不能正確導入通過using
。
請注意,當我不使用OverloadFuncImpl
或排除OverloadFuncImpl
的函數部分專業化時,上面的代碼工作得很好。
我已經得到了這個代碼工作的解決方法,但我只是想知道爲什麼上面的代碼不起作用。我似乎無法弄清楚......爲什麼當我導入了所有基類的所有operator()
。仍然存在模糊的過載問題?
我試圖重現錯誤在一個較小的範圍內,但無法...
順便說一句,這與您的問題沒有直接關係,但是:您的函數指針實現有更多問題。只要嘗試從一個函數指針創建一個重載,該指針需要一個右值引用。 –
@NirFriedman你在說什麼?構造函數或調用操作符? – Curious
呼叫運營商。 http://coliru.stacked-crooked.com/a/2d3469ea05c357c1 –