使用模板函数指针声明模板函数
我第一次同时使用模板和指向成员函数的指针,我偶然发现了以下问题。
我为 typedef 声明了一个 struct Proxy,因为模板和 typedef 不能一起工作(我知道这在 C++11 中应该是可能的,但 MSVC++ 不接受它)。现在我想声明一个模板化(!)函数,它使用具有模板类型的代理。这就是导致编译时出错的原因。请看一下下面的(简化的)代码,我添加了一些示例来澄清问题。
我正在使用标准 VC++ 2010(无 CLR/CLI)。
template<typename T>
struct Proxy
{
typedef bool (CClass::*MethodPtr)(const T* const objectX);
}
class CClass
{
// warning: dependent name is not a type
// error:: Method can not be a template definition
template<typename T>
bool Method( Proxy<T>::MethodPtr );
// this works, but i want to specify T instead of int of course
template<typename t>
bool method( Proxy<int>::MethodPtr );
// this is what i use
template<typename T>
bool Method( bool (CClass::*MethodPtr)(const T* const objectX) );
}
template<typename T>
bool CClass::Method( bool (CClass::*MethodPtr)(const T* const objectX) )
{
// next line compiles without problems
Proxy<T>::MethodPtr ptr2;
}
First time I use templates and pointer to member functions at the same time and I stumbled across following problem.
I declared a struct Proxy for a typedef, since templates and typedefs are not working together (I know this should be possible in C++11, MSVC++ does not accept it though). Now I want to declare a templated(!) function which uses the proxy with the templates type. This is what causes the error at compilation. Please have a look at the (simplified) code below, I added some examples to clarify the problem.
I am working with standard VC++ 2010 (no CLR/CLI).
template<typename T>
struct Proxy
{
typedef bool (CClass::*MethodPtr)(const T* const objectX);
}
class CClass
{
// warning: dependent name is not a type
// error:: Method can not be a template definition
template<typename T>
bool Method( Proxy<T>::MethodPtr );
// this works, but i want to specify T instead of int of course
template<typename t>
bool method( Proxy<int>::MethodPtr );
// this is what i use
template<typename T>
bool Method( bool (CClass::*MethodPtr)(const T* const objectX) );
}
template<typename T>
bool CClass::Method( bool (CClass::*MethodPtr)(const T* const objectX) )
{
// next line compiles without problems
Proxy<T>::MethodPtr ptr2;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
typename
来指示依赖名称是类型;特别是,Method
的第一个声明应该是:你所说的编译没有问题的行(但只是因为 VC++ 有一个接受格式错误的代码的“扩展”)应该是
:类定义之后也缺少分号,并且在
Proxy
定义之前缺少CClass
的前向声明。You need to use
typename
to indicate where a dependent name is a type; in particular, the first declaration ofMethod
should be:and the line that you say compiles without problems (but only because VC++ has an "extension" that accepts ill-formed code) should be:
You're also missing semicolons after the class definitions, and a forward declaration of
CClass
before the definition ofProxy
.MethodPtr
依赖于模板参数T
,您应该使用typename
。您也应该在那里使用
typename
,不确定为什么它会编译。MethodPtr
is dependent on template argumentT
, you should be usingtypename
.You should use
typename
there as well, not sure why it compiles.