use*_*740 5 c++ templates specialization class-template
noob在这里仍在试验模板.试图编写一个消息处理类模板
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_
};
Run Code Online (Sandbox Code Playgroud)
全部在头文件中定义.我已经建立并测试了我的课程,一切都很好.现在,我正在尝试这样做:
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_;
};
Run Code Online (Sandbox Code Playgroud)
但是,这行在">"标记之前给出了错误表达式类型的错误.
我添加了必要的头文件来定义MessageType是什么.我之前很久就使用过这个函数,只是不是在这种情况下.
我怀疑编译器不喜欢模板函数在未定义的类模板(unspecialized?)中完全定义(专用?)的事实.我并不完全了解模板"专业化"的原因.大多数解释都集中在"完整"或"部分"的概念上,而不是首先使它成为专业的概念.
如果您想查看更多代码,请道歉.我在工作时没有互联网接入,这就是我正在做的事情,所以我必须将所有内容放入我的心理"暂存器"并将其带回家.
你的成员函数'foo'需要一个返回类型,你需要在依赖表达式中使用成员模板时使用关键字'template'(表达式的含义直接或间接依赖于通用模板参数)
t_->template getMessageSender<MessageType>(); // ok
t_->getMessageSender<MessageType>(); // not ok
Run Code Online (Sandbox Code Playgroud)
当成员模板需要以'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
}
};
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
| 归档时间: |
|
| 查看次数: |
12171 次 |
| 最近记录: |