C++11:通用执行器

2024-04-27

我想知道如何编译此代码:

// 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;
}

错误消息(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'

我如何指示正确的过载addition功能?


将您的主要替换为

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

    // or alternatively
    // cout << universal_exer((int (*)(int))addition, 1) << endl;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++11:通用执行器 的相关文章

随机推荐