【发布时间】:2019-08-20 05:36:03
【问题描述】:
我正在开发一个具有以下结构的程序:
#include <iostream>
#include <string>
void fun(const std::string &text, int a, int b) { // (1)
std::cout << text << a + b << std::endl;
}
template<typename ...Args>
void execute(void(*fun)(Args...), Args ...args) {
fun(args...);
}
void init(const std::string &text, int a, int b) {
execute(fun, text, a, b);
}
int main() {
init("Fun: ", 1, 2);
return 0;
}
我收到错误消息
.code.tio.cpp:14:2: error: no matching function for call to 'execute'
execute(fun, text, a, b);
^~~~~~~
.code.tio.cpp:9:6: note: candidate template ignored: deduced conflicting types for parameter 'Args' (<const std::__cxx11::basic_string<char> &, int, int> vs. <std::__cxx11::basic_string<char>, int, int>)
void execute(void(*fun)(Args...), Args ...args) {
^
1 error generated.
我可以通过删除第 (1) 行中的引用来修复错误:
void fun(const std::string text, int a, int b) {
但我想通过引用而不是值传递值。函数模板
template<typename ...Args>
void execute(void(*fun)(Args...), Args ...args)
不得更改。我该如何解决这个问题,以便 text 通过引用传递,execute 不会更改,init 也不会更改(如果可能)?
编辑:
@super 表明我错了,我必须重新制定我的要求。 execute 只能在其他依赖此函数的项目不中断的情况下进行修改。我没有想过这样的解决方案。
【问题讨论】:
-
您的代码不起作用,但您不想更改它?在这种情况下,我不明白你在寻找什么。
-
@super 我无法更改
execute,因为它是许多不同项目中使用的框架的通用函数。不可能改变它。init可以更改,但会很昂贵。fun可以更改,因为它是必须与通用框架一起使用的新功能
标签: c++ c++11 templates variadic-templates template-argument-deduction