Tại sao không thể khấu trừ F
cho proxy()
?Không thể suy luận đối số mẫu là hàm
Điều này có thể xảy ra vì tôi đang hạn chế nó - chỉ cho các chức năng trả về int
.
#include <utility>
#include <iostream>
#include <type_traits>
using namespace std;
int foo(int bar) {
cout << "int" << endl;
return 2;
}
float foo(float bar) {
cout << "float" << endl;
return 1;
}
template <typename F, typename... Args>
typename enable_if<
is_same<
typename result_of<F(Args...)>::type,
int
>::value,
typename result_of<F(Args...)>::type
>::type
proxy(F func, Args&&... args) {
return func(forward<Args>(args)...);
}
int main() {
proxy(foo, 5);
}
Dưới đây là lỗi:
b.cpp:29:17: error: no matching function for call to 'proxy(<unresolved overloaded function type>, int)'
b.cpp:24:1: note: template argument deduction/substitution failed:
b.cpp:29:17: note: couldn't deduce template parameter 'F'
Như có hai quá tải của hàm ... Trình biên dịch không thể suy ra giá trị trên cơ sở của một tương lai (tiếp theo) tham số của một hàm ...'proxy (static_cast (foo), 5);' sẽ làm thủ thuật ở đây –