防止未使用的默认函数参数的实例化
假设我有一个函数,它接受函数指针作为参数,并且该参数有一个默认参数。
template <typename T>
T* default_construct()
{
return new T();
}
template <typename T>
void register(T* (*construct)() = default_construct<T>)
{
// Save that function pointer for later
}
假设我想在我的类 Foo
上使用 register,但是 Foo
没有默认构造函数,所以我的 default_construct
将无法工作在它上面。显而易见的解决方案是做这样的事情:
Foo* construct_Foo()
{
return new Foo("String argument", 123);
}
SomeFunc()
{
// ...
register<Foo>(construct_Foo);
// ...
}
但这不起作用。即使 register
只能在一个地方调用,并且它传递了一个要使用的函数,default_construct
仍然会被编译器实例化,我得到编译器错误。似乎因为它从未被使用过,所以应该跳过它,但我想事实并非如此。
有什么方法可以防止 default_construct
在用作默认参数时被实例化?我能想到的唯一解决方案是将其放入模板中,但似乎应该有更好的解决方案。
Lets say I have a function which takes a function pointer as a parameter, and that parameter has a default argument.
template <typename T>
T* default_construct()
{
return new T();
}
template <typename T>
void register(T* (*construct)() = default_construct<T>)
{
// Save that function pointer for later
}
Lets say I want to use register on my class Foo
, but Foo
doesn't have a default constructor, so my default_construct
won't work on it. The obvious solution is to do something like this:
Foo* construct_Foo()
{
return new Foo("String argument", 123);
}
SomeFunc()
{
// ...
register<Foo>(construct_Foo);
// ...
}
But that doesn't work. Even though register<Foo>
may only be called in one place, and it's passed a function to use, default_construct<Foo>
still gets instantiated by the compiler, and I get compiler errors. It seems like since it never gets used, it ought to be skipped over, but I guess that's not the case.
Is there any way to prevent default_construct
from being instantiated when it's being used as a default argument? The only solution I can think of is to put it in the template, but it seems like there ought to be a better solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是解决该问题的一种解决方案,因为它不使用默认参数:
请注意,
register
是一个 C++ 关键字:)Here's one solution that solves the problem because it doesn't use default arguments:
Note that
register
is a C++ keyword though :)