c++ - 如何将 vector 中的可变参数转换为它是参数的持有者?

标签 c++ c++11 variadic-templates move-semantics perfect-forwarding

我找到了 this solution .它有效,但我希望我的类(class)是争论的所有者。我有下一个代码:

template <class val_t>
class exp_t {
public:
    exp_t() {}
    virtual ~exp_t() {}

    virtual bool is(const std::vector<val_t> &kb) const = 0;
};

template <class val_t>
class fact_t: exp_t<val_t> {
public:
    const val_t m_value;

    fact_t(const val_t value): m_value{value} {}

    virtual bool is(const std::vector<val_t> &kb) const {
        return std::find(kb.begin(), kb.end(), m_value) != kb.end();
    }
};

template <class val_t>
class not_t: public exp_t<val_t> {
    exp_t<val_t> m_exp;
public:
    not_t(exp_t<val_t> exp): exp_t<val_t>(), m_exp{exp} {}

    virtual bool is(const std::vector<val_t> &kb) const override {
        return !m_exp.is(kb);
    }
};

template <class val_t, class ... args_t>
class and_t: public exp_t<val_t> {
    std::vector<exp_t<val_t>> m_exps;
public:
    and_t(args_t... exps) : exp_t<val_t>(), m_exps{{exps...}} {}

    virtual bool is(const std::vector<val_t> &kb) const override {
        for (auto &exp : m_exps) {
            if (!exp.is(kb)) { return false; }
        }

        return true;
    }
};

我需要我可以写一个像下面这样的东西:

exp_t<int> *get_exp() {  
    return new and_t<int>(fact_t<int>(5), fact_t<int>(6));
}

即我可以返回我的 exp_t 并保存传递的参数(例如使用 move 语义,我知道如何使类可 move ,但我不知道如何重写 and_t构造函数传递它并转换为 std::vector).
如何更改我的类(class) and_t?在 C++ 中可能吗?

P.S. 我试图自己阅读有关可变参数的内容,但我什么都不懂。

最佳答案

I.e. to I could return my exp_t and it saved passed arguments (for example using move semantic, I know how to make classes movable, but I don't know how to rewrite and_t constructor to pass it and convert to the std::vector)

如果您知道(如果您确定)所有参数都是右值,您可以使用如下 move 语义

 and_t (args_t && ... exps)
    : exp_t<val_t>(), m_exps{{std::move(exps)...}}
  { }

否则(如果一些参数可以是右值,一些是左值),你可以使用完美转发

template <typename ... Args>
and_t (Args && ... exps)
   : exp_t<val_t>(), m_exps{{std::forward<Args>(exps)...}}
 { }

因此您 move 右值并复制左值。

我想最好的方法是第二种(完美转发),所以不需要 args_t 类型的可变列表 and_t 类。

关于c++ - 如何将 vector 中的可变参数转换为它是参数的持有者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52825063/

相关文章:

c++ - ZeroMq:打开的文件太多。同一对象上的 fd 使用量持续增长

c++ - 从静态库函数访问文本数据文件

linux - Linux 上如何创建互斥锁?

c++ - 为什么当类的数据成员更改为引用时输出不同

c++ - 在 C++ 中格式化未知长度的字符串

c++ - "Inheriting"具有可变模板函数的类

函数执行器中的 C++ 歧义,参数在 vector 中传递

c++ - 编译时素数列表 : specialization error

c++ - 按类型获取具有递归继承的可变参数模板的阴影成员

c++ - 链式ostream内部行为及其在MSVC上的结果(与Clang相比)