-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Open
Description
我之前对template这部分内容了解不多,这份教程对我帮助很大!
但是在3.2章里面有两个地方没有搞明白,希望能得到一些指点。
第一个问题:
但是问题到了这里并没有结束。因为 increase 毕竟是个虚函数。假如 Counter 需要调用的地方实在是太多了,这个时候我们会非常期望 increase 不再是个虚函数以提高性能。此时我们会调整继承层级:
struct ICounter {};
struct Counter: public ICounter {
void increase() {
// impl
}
};
template <typename T>
void inc_counter(ICounter& c) {};
template <typename T>
void inc_counter(T& c) { ++c; };
void doSomething() {
Counter cntObj;
uint32_t cntUI32;
// blah blah blah
inc_counter(cntObj); // 1
inc_counter(static_cast<ICounter&>(cntObj)); // 2
inc_counter(cntUI32); // 3
}
这里基类ICounter是个无用的tag,但是在inc_counter(static_cast<ICounter&>(cntObj)); // 2中,将cntObj转为ICounter后,基类里并没有increase()这个函数呀。要怎么实现计数的功能呢?
所以这个地方没有理解。
第二个问题
仍是上面这份代码里的inc_counter(static_cast<ICounter&>(cntObj)); // 2,想要调用的应该是
template <typename T>
void inc_counter(ICounter& c) {};
这个函数吧?但是这样会报错(用c++11/c++14都试过,估计与c++标准的版本无关):
error: no matching function for call to 'inc_counter'
inc_counter(static_cast<ICounter&>(cntObj));
^~~~~~~~~~~~
请问这里是想要表达为:
template <typename T>
void inc_counter(T &c) {
}
template <>
void inc_counter(ICounter &c) {
std::cout << "in ICounter" << std::endl;
}
还是直接:
void inc_counter(ICounter& c) {};
另外,为什么会有这样的报错,我也不是很确定。
望指教,非常感谢!
Metadata
Metadata
Assignees
Labels
No labels