使用模板而不是 cpp 预处理器来避免链接?
是否可以使用 C++ 模板来避免链接包含最终未调用的函数的库?例如,使用如下代码:
template <typename T>
struct Foo {
void bar() { zod(); }
};
int main(int argc, char *argv[])
{
return 0;
}
GCC 4.5 将拒绝它: 错误:“zod”没有依赖于模板参数的参数,因此“zod”的声明必须可用 注意:(如果您使用“-fpermissive”,G++ 将接受您的代码,但不推荐使用未声明的名称)
按照标准,此处是否必须出现错误?有没有办法使用模板来实现这一点;因此避免使用 cpp 宏。
Is it possible to use C++ templates to avoid linking against a library containing a function which is not ultimately called? For example, with code such as:
template <typename T>
struct Foo {
void bar() { zod(); }
};
int main(int argc, char *argv[])
{
return 0;
}
GCC 4.5 will reject it:
error: there are no arguments to ‘zod’ that depend on a template parameter, so a declaration of ‘zod’ must be available
note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
Is an error compulsory here by standard? Is there any way using templates to achieve this; and so avoid cpp macros.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您将链接与为
zod()
提供原型(即声明,例如通过包含头文件)混淆了。许多实现会愉快地编译和链接具有内联函数(或模板)的程序,这些函数调用没有定义的函数。所以,这工作得很好(至少适用于 MSVC 10、GCC 4.3 和 GCC 4.5):
但我不确定标准是否强制这样做。当然,只要模板从未实例化,它也应该使用模板而不是内联。
I think you're confusing linking with providing a prototype for
zod()
(i.e. a declaration, e.g. by including a header file).Many implementations will happily compile and link a program that has
inline
functions (or templates) which call functions without a definition. So, this works just fine (with at least MSVC 10, GCC 4.3 and GCC 4.5):I'm not sure if the standard mandates it though. And of course it should also work with a template instead of
inline
, as long as the template is never instantiated.正如错误所暗示的那样,如果 zod() 依赖于模板参数,那么 SFINAE 会将其视为不是问题。
按照目前的情况,
zod
声明必须可用。对不起。如果您可以控制 zod 并且不介意向其添加虚拟参数,您可以执行以下操作:
但是...主要是。
As the error implies, if
zod()
had a dependency on a template parameter then SFINAE would render this as not-a-problem.As it stands, a declaration of
zod
must be available. Sorry.If you had control of
zod
and didn't mind adding a dummy parameter to it, you could do something like this:But... major ew.
您没有在示例中显示任何需要对代码进行专门化的内容。在这种情况下,您只需将函数声明为内联即可。
也许这个问题还有更多我没有看到的内容;如果是这样,请编辑问题并提供更多详细信息。
You haven't shown anything in your example that needs any specialization of the code. In that case you can simply declare the function
inline
.Perhaps there's more to the question that I'm not seeing; if so, please edit the question and provide more details.