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

标签 c++ templates

我正在学习一些有关 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/

相关文章:

c++ - 结构的 "type"是否会因计算机而异?

c++ - 制作一个指向已分配内存的 C++ vector

c++ - 继承自 QListWidget 及其 SLOT

c++ - 成员指针数组(偏移量)作为 C++ 中的模板参数

c++ - 非模板代码有效时,模板代码无效!

c++ - 使用来自可变参数模板类的特定参数调用函数

c++ - `n`中的 `const n = 1u;`有什么类型?

node.js - html-webpack-plugin - 如何在不执行 EJS 模板的情况下插入 webpack bundle.js

c++ - 抽象类的模板实例化

c++ - 检测模板化类型本身是否是模板化类型