5

tôi sẽ biết làm thế nào có được mã này biên dịch:C++ 11: Universal thi hành di chúc

// test3.cpp                                              

#include <iostream> 

using namespace std; 

template<typename R, typename... rArgs> 
R universal_exer(R(*f)(rArgs...), rArgs... args) 
{ 
    return (*f)(forward<rArgs>(args)...); 
} 

int addition(int a) 
{ 
    return a; 
} 

int addition(int a, int b) 
{ 
    return a + b; 
} 

template<typename... Args> 
int addition(int a, int b, Args... args) 
{ 
    return a + b + addition(args...); 
} 

int main() 
{ 
    cout << universal_exer(&addition, 1) << endl; 
} 

Thông báo lỗi (gcc 4.7.2):

test3.cpp: In function 'int main()': 
test3.cpp:31:40: error: no matching function for call to 'universal_exer(<unresolved overloaded function type>, int)' 
test3.cpp:31:40: note: candidate is: 
test3.cpp:8:3: note: template<class R, class ... rArgs> R universal_exer(R (*)(rArgs ...), rArgs ...) 
test3.cpp:8:3: note: template argument deduction/substitution failed: 
test3.cpp:31:40: note: couldn't deduce template parameter 'R' 

Làm thế nào tôi có thể chỉ ra sự quá tải đúng của hàm addition?

+1

Cast nó để con trỏ bên phải (giúp cho quá tải) hoặc sử dụng một lambda, có một dupe đâu đó. – inf

+0

thử this 'cout << universal_exer (static_cast (& bổ sung), 1) << endl;' [ví dụ] (https://godbolt.org/g/fLMZRm) – Nyufu

Trả lời

5

Thay thế chính của bạn với

int main() 
{ 
    int (*f)(int) = &addition; 
    cout << universal_exer(f, 1) << endl; 

    // or alternatively 
    // cout << universal_exer((int (*)(int))addition, 1) << endl; 
} 
+4

Cụ thể, giải pháp cho 'loại chức năng quá tải chưa được giải quyết' là để giải quyết * mà * chức năng quá tải. Điều đó đang được thực hiện ở đây. –