功能默认参数将被忽略

时间:2017-09-13 19:37:45

标签: c++ c++11 templates g++

对于这段简化的代码,我收到了以下错误:

  

错误:函数参数太少     std :: cout<< F();

int g(int a = 2, int b = 1)
{
    return a + b;
}

template<class Func>
void generic(Func f)
{
    std::cout << f();
}

int main()
{
    generic(g);
}

我无法弄清楚为什么函数f的默认参数没有传递给函数generic的原因。它的行为类似于f没有任何默认参数...

那里有什么问题?

如何正确转发默认参数?

2 个答案:

答案 0 :(得分:22)

g可能有默认参数,但&g的类型仍为int(*)(int, int),这不是可以不带参数调用的类型。在generic内,我们无法区分 - 我们已经失去了关于默认参数的上下文。

您可以将g包装在lambda中以保留上下文:

generic([]{ return g(); });

答案 1 :(得分:7)

我认为此代码的错误消息很好地说明了为什么这是不可能的:

int g(int a=0,int b=0){return 0;}

typedef int (*F1)(int);

int main() {
    F1 x = g;
}

error: cannot initialize a variable of type 'F1' (aka 'int (*)(int)') with
an lvalue of type 'int (int, int)': different number of parameters (1 vs 2)
    F1 x = g;
       ^   ~

即使使用默认参数,g的类型仍然是

int (*) (int,int)

这是实例化模板时推断的内容。

如果出于某种原因你不能使用C ++ 11或更高版本(即没有lambdas,请参阅Barry的答案)并且你不介意一点样板,那么你可以使用一个函数对象:

#include <iostream>

struct g_functor {
    int operator()(int a=0,int b=0){ return a;}
};

template <typename T> void foo(T t) { t(); }

int main() { foo(g_functor()); }

请注意,您必须创建g_functor的实例才能将其作为参数传递。