代码可能比文字更好地解释我的问题:
#include <string>
struct Something {};
struct Context
{
std::string GetUniqueInentifier()
{
return "";
}
// ERROR
void Register(const Something& something, const std::string& key = GetUniqueInentifier())
{
}
};
int main()
{
Context c;
c.Register(Something{}); //<- want to be able to do this
// and a unique identifier will
// be automatically assigned
c.Register(Something{}, "Some Key"); //<- want to be able to let the user
// pick an identifier if they want
}
这显然是不允许的,但我该如何模拟这种行为呢?
不能使用非static
成员函数或变量作为成员函数的默认值。由于GetUniqueInentifier()
返回的值不需要Context
的实例,因此将其设为static
,然后您可以在尝试使用它时使用它。
static std::string GetUniqueInentifier()
{
return "";
}