【发布时间】:2011-11-20 20:18:56
【问题描述】:
我有两个奇怪的情况,看起来代码应该编译,但事实并非如此。首先,考虑下面的代码,它编译成功:
struct A
{
template <class T>
void member_func(T t)
{
global_func(t);
}
};
int main()
{
}
但如果我通过前缀“::”来完全限定 global_func,它不会编译并出现错误“'global_func' is not declared in this scope”:
struct A
{
template <class T>
void member_func(T t)
{
::global_func(t);
}
};
int main()
{
}
另外,如果我尝试将 global_func 传递给 boost::bind,它不会编译(同样的错误):
#include <boost/bind.hpp>
class A
{
template <class T>
void member_func(T t)
{
boost::bind(global_func)(t);
}
};
int main()
{
}
为什么在这些情况下它不能编译?好像 member_func() 模板方法没有被实例化,所以它不应该找到缺少的函数错误。
【问题讨论】:
-
你不需要这样的代码:void global_func(int a);无效 global_func(float b);等等?
-
您的第一个和第二个示例是相同的,您可能需要编辑。
-
@tp1 - 据我了解 - 不。这个想法是,模板在需要时被实例化。并且由于没有人实例化这个模板函数(例如——调用这个成员函数或创建的对象
A),所以应该没有编译错误。 -
有趣。我明白为什么 ::global_func 不会被视为“取决于模板参数”,但
bind样本应该等同于第一个 -
@themel 好像有人帮我修好了,谢谢!
标签: c++ templates compilation