CppTemplateTutorial
CppTemplateTutorial copied to clipboard
请教3.2章中两个问题
我之前对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) {};
另外,为什么会有这样的报错,我也不是很确定。
望指教,非常感谢!
同问:
我们看看 enable_if 是怎么解决这个问题的。我们通过 enable_if 这个 T 对于不同的实例做个限定:
下面这段代码的编译结果:
/opt/compiler-explorer/gcc-12.2.0/bin/../lib/gcc/x86_64-linux-gnu/12.2.0/../../../../x86_64-linux-gnu/bin/ld: /tmp/ccdgLfcf.o: in function `doSomething()':
<source>:31: undefined reference to `void inc_counter<unsigned int>(unsigned int&, std::enable_if<std::is_integral<unsigned int>::value, void>::type*)'
collect2: error: ld returned 1 exit status
Compiler returned: 1
当然,这与编译无关,不过为啥会link错误,求教
害,没有impl. 我又晕了
OK
害,没有impl. 我又晕了
嗯嗯。还有别的问题吗
OK
害,没有impl. 我又晕了
嗯嗯。还有别的问题吗
没有~ thx