C++11:通用执行器

标签 c++ templates c++11 overloading overload-resolution

我想知道如何编译这段代码:

// 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 函数的正确重载?

最佳答案

用 main 替换

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

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

关于C++11:通用执行器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15506427/

相关文章:

C++封装数组

c++ - 返回本地对象的元组

javascript - 服务器端的 jQuery 模板

c++ - ADL 找不到重载函数

c++ - 了解勘误表中有关 EMC++ 第 41 项的评论

c++ - 当为不存在的日期/时间设置 CreateWaitableTimer 时会发生什么?

C++模板类编译报错信息: error: expected a qualified name after 'typename'

c++ - 将自己的 C++ 类添加到现有的 MFC 应用程序中

javascript - asp中继器模板条件验证javascript

c++ - libstdc++ 在 Mac 上找不到线程文件