c++ - 从类的类型结构中获取值

标签 c++ templates

这就是我的代码的样子。它有点简化。我正在尝试/想知道我是否可以做的是消除属性类构造函数中对参数的需要。即调用无参数构造函数,并且仍然能够使用 struct value1 项变量填充类项变量,而无需将它们添加为构造函数主体的一部分。

#include <iostream>

using namespace std;

struct value1
{
    const int item;
    value1( int n ) : item(n) { }
};

struct value2 : public value1
{
    value2() : value1(55) { };
};

template <class T>
class property
{
public:
    property(T stuff);
    void print();
private:
    int item;
};

template <class T>
property<T>::property(T stuff) : item(stuff.item) { }

template <class T>
void property<T>::print()
{
    cout << item << endl;
}

int main()
{
    property<value2> *y = new property<value2>(value2());

    y->print();

    return 0;
}

最佳答案

call a no arg constructor and still be able to populate the classes item variable with the struct value1 item variable without adding them as part of the constructors body

听起来您只是想要一个工厂方法:

template <class T>
class property {
public:
    property();
    void print();

    static property<T> create(T stuff) {
        property<T> p;
        p.item = stuff.item;
        return p;
    }

private:
    int item;
};

您可以按如下方式调用它:

auto p = property<value2>::create(value2());

即使我不确定我是否完全符合您的要求。
让我知道,如果我不明白问题,我会删除答案。

关于c++ - 从类的类型结构中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39647264/

相关文章:

java - 创建评估新创建的变量的代码模板

c++ - 为什么从方法返回时局部变量中的数据会损坏?

c++ - 指向多维数组第 n 个元素的指针

c# - wcf:调试 native c++ dll?

C++ 函数式 : bind classes method through pointer

c++ - 使变量在作用域中途不可用/不可访问

c++ - 如何与特定模板特化成为 friend ?

Java 表达式语言 : Interpolation?

javascript - 如何在 Handlebars 模板中插入 JavaScript 代码?

c++ - 我可以 typedef 模板模板参数吗?