gpt4 book ai didi

c++ - 用类参数化的类和与辅助函数的混淆

转载 作者:太空狗 更新时间:2023-10-29 21:13:04 25 4
gpt4 key购买 nike

我正在学习一些有关 C++ 的新概念,并且正在使用它们。我写了一段代码,但它的工作原理让我很困惑。

#include <iostream>

class aid {
public:
using aid_t = std::string;
void setaid(const std::string& s) {
aid_ = s;
}
const aid_t& getaid() const {
return aid_;
}
private:
aid_t aid_;
};

class c {
public:
using c_t = std::string;
void setc(const aid::aid_t& aid_val) {
if (aid_val.size() < 4)
c_ = "yeah";
else
c_ = aid_val + aid_val;
}
const c_t& getc() {
return c_;
}
private:
c_t c_;
};

template<typename ...Columns>
class table : public Columns... {
};

template <typename... Columns>
void f(table<Columns...>& t) {
t.setaid("second");
std::cout << t.getaid() << "\n";
}

void f2(table<aid>& t) {
t.setaid("third");
std::cout << t.getaid() << "\n";
}

int main() {
table<aid, c> tb;
tb.setaid("first");
std::cout << tb.getaid() << " " << "\n";
// f<c>(tb); // (1) doesnt compile, that seem obvious
f<aid>(tb); // (2) works?
f(tb); // (3) works too -- template parameter deduction
// f2(tb); // (4) doesnt work? worked with (2)...
}

这里的想法很简单,我有一些带有列的表格。然后我想创建一些只需要一些列集的函数,而不关心传递的参数是否有一些额外的列。

我的困惑主要是关于代码中的第 (2) 点和 (4) 点……我的直觉告诉我它应该是相同的,为什么它不是并且 (2) 编译而 (4) 不?有什么我遗漏的重要主题应该阅读吗?有没有办法实现这个特定的功能?

最佳答案

在第二种情况下,编译器仍然推导模板参数包的其余部分,这样你就可以得到table<aid, c> &。作为函数参数。这与 (4) ( table<aid> & ) 不同。

[temp.arg.explicit]/9 :

Template argument deduction can extend the sequence of template arguments corresponding to a template parameter pack, even when the sequence contains explicitly specified template arguments.

关于c++ - 用类参数化的类和与辅助函数的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45628592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com