CppTemplateTutorial icon indicating copy to clipboard operation
CppTemplateTutorial copied to clipboard

请教3.2章中两个问题

Open PeiMu opened this issue 3 years ago • 4 comments

我之前对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) {};

另外,为什么会有这样的报错,我也不是很确定。

望指教,非常感谢!

PeiMu avatar Feb 25 '21 08:02 PeiMu

同问: 我们看看 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错误,求教

ijpq avatar Jan 16 '23 15:01 ijpq

害,没有impl. 我又晕了 image

ijpq avatar Jan 16 '23 15:01 ijpq

OK

害,没有impl. 我又晕了 image

嗯嗯。还有别的问题吗

wuye9036 avatar Jan 17 '23 23:01 wuye9036

OK

害,没有impl. 我又晕了 image

嗯嗯。还有别的问题吗

没有~ thx

ijpq avatar Jan 28 '23 06:01 ijpq