Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

请教3.2章中两个问题 #63

Open
PeiMu opened this issue Feb 25, 2021 · 4 comments
Open

请教3.2章中两个问题 #63

PeiMu opened this issue Feb 25, 2021 · 4 comments

Comments

@PeiMu
Copy link

PeiMu commented Feb 25, 2021

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

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

望指教,非常感谢!

@ijpq
Copy link

ijpq commented Jan 16, 2023

同问:
我们看看 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
Copy link

ijpq commented Jan 16, 2023

害,没有impl. 我又晕了
image

@wuye9036
Copy link
Owner

OK

害,没有impl. 我又晕了 image

嗯嗯。还有别的问题吗

@ijpq
Copy link

ijpq commented Jan 28, 2023

OK

害,没有impl. 我又晕了 image

嗯嗯。还有别的问题吗

没有~ thx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants