【问题标题】:Caller function with optional argument of varying type具有不同类型的可选参数的调用者函数
【发布时间】:2020-02-20 05:26:24
【问题描述】:

我正在尝试编写一个调用函数,它可以采用不同模板类型的可选参数。

#include <iostream>
#include <string>

void f_int(int x){std::cout << "f_int\n";}
void f_double(double x){std::cout << "f_double\n";}
void f_void(void){std::cout << "f_void\n";}

template<typename T>
void caller(void (*fun)(T), T arg)
{
    (*fun)(arg); 
}


int main()
{
  caller(f_int, 3);
  caller(f_double, 2.1);
  caller(f_void);         // compilation error
  caller(f_void, void);   // compilation error
  void* p;
  caller(f_void, *p);     // compilation error
}

在编写这段代码时,我希望T 可以是void 类型。是真的吗?如果是,为什么上面的代码不起作用? void 是有效类型还是只有 void* 是有效类型?

【问题讨论】:

  • f_void 有零个函数参数,*fun 给定void (*fun)(T) 有一个函数参数,所以它们永远不会匹配。将(void) 作为函数参数列表的意思与() 相同只是支持C 习惯的一个特例,不适用于后来确定为void 的模板依赖类型。

标签: c++ function compiler-errors void


【解决方案1】:

您可以使用variadic template 和perfect forwarding 完成大部分操作:

template<typename F, class... Args>
void caller(F func, Args&&... args) {
    func(std::forward<Args>(args)...);
}

//...

caller(f_int, 3);
caller(f_double, 2.1);
caller(f_void);

你也可以使用auto从函数模板中返回被调用函数的值,即使被调用函数声明为void:

int f_int(int x) {
    return x*2;
}
double f_double(double x) {
    return x*1.5;
}
void f_void(void) {
    std::cout << "f_void\n";
}

template<typename F, class... Args>
auto caller(F func, Args&&... args) {          // note the "auto"
    return func(std::forward<Args>(args)...);  // and return
}

//...

auto rv1 = caller(f_int, 3);
auto rv2 = caller(f_double, 2.1);
caller(f_void);                                // you can't assign void though

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-23
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多