菜鸟还在尝试模板。尝试写一个消息处理类模板
template <typename T> class MessageProcessor {
//constructor, destructor defined
//Code using t_ and other functions
foo( void ) {
//More code in a perfectly fine method
}
private: T *t_
};
全部定义在一个头文件中。我已经构建并测试了我的类(class),一切都很好。现在,我正在尝试这样做:
template <typename T> class MessageProcesor {
//Same stuff as before
foo(void) {
//Same code as before in foo, but one new line:
t_->getMessageSender<MessageType>();
}
private: T *t_;
};
但是,这一行在“>”标记之前给我一个错误的表达式类型错误。
我已经添加了必要的头文件来定义 MessageType 是什么。我以前多次使用过这个功能,只是不是在这种情况下。
我怀疑编译器不喜欢模板函数在未定义的类模板(未专门化?)中完全定义(专门化?)这一事实。我没有完全理解是什么让模板“特化”。大多数解释都集中在“完整”或“部分”的概念上,而不是首先使它专门化的原因。
如果您想查看更多代码,我们深表歉意。我在工作中无法访问互联网,这就是我做这件事的地方,所以我必须把所有东西都放在我的精神“便签本”中,然后把它带回家。
最佳答案
你的成员函数 'foo' 需要一个返回类型,当你在依赖表达式(其含义直接或间接依赖于通用模板参数的表达式)中使用成员模板时,你需要使用关键字 'template'
t_->template getMessageSender<MessageType>(); // ok
t_->getMessageSender<MessageType>(); // not ok
也许这个例子将帮助您了解成员模板需要以"template"关键字作为前缀[注意:为了对称起见,您可以始终在成员上使用"template"前缀模板,但在非依赖表达式上使用时是可选的。
struct MyType
{
template<class T> void foo() { }
};
template<class U>
struct S
{
template<class T>
void bar()
{
MyType mt; // non-dependent on any template parameter
mt.template foo<int>(); // ok
mt.foo<int>(); // also ok
// 't' is dependent on template parameter T
T t;
t.template foo<int>(); // ok
t.foo<int>(); // not ok
S<T> st; // 'st' is dependent on template parameter T
st.template foo<int>(); // ok
st.foo<int>(); // not ok
S<MyType> s; // non-dependent on any template parameter
s.bar<int>(); // ok
s.template bar<int>(); // also ok
}
};
希望对您有所帮助。
关于c++ - C++中类模板内的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1090819/