结构中的模板值是否可以包含对象?

时间:2017-02-06 15:58:36

标签: c++ templates object struct constructor

如果我有像

这样的结构
template<typename T>
struct element{
    T val;
};

val可以成为一个对象吗?如果有可能我该怎么做,编译器会告诉我constructor for element<object> must explicitly initialize the member val which does not have a default constructor

1 个答案:

答案 0 :(得分:2)

  

val可以成为一个对象吗?

是。演示:

element<int>

结构int包含constructor for element<object> must explicitly initialize the member val which does not have a default constructor. 类型的成员对象。

element
正如您所定义的那样

val将默认构建T成员。因此,它要求element是默认可构造的。此限制与element是模板的事实无关,它也适用于非模板。

错误消息告诉您已使用不是默认可构造的类型参数实例化模板。要支持此类型,您需要template<typename T> struct element{ T val; template<class... Args> element(Args&&... args) : val(std::forward<Args>(args)...) {} }; // ... element<non_default_constructible> e(42); 的自定义构造函数。例如:

template<typename T>
struct element{
    T val;

    element(T other)
    : val(other)
    {}
};
  

如果我不能使用c ++ 11怎么办?

您可以按副本初始化该成员。这当然要求包装类型必须是可复制的:

seqExe(["item one", "item two", "item three", "item four", "item five"])

function seqExe(corpus) {
    var i = -1,
        len = corpus.length,
        defer = jQuery.Deferred(),
        promise = defer.promise();

    while(++i < len) {
        promise = promise.then((function(item) {
            return function() {
                console.log(item);
                return foo(item);
            }
        }).call(this, corpus[i]));
    }

    promise.then(function() {
        console.log("Done");
    }, function() {
        console.error("Failed");
    });

    return defer.resolve();
}

function foo(item) {
    var defer = jQuery.Deferred();
    window.setTimeout(
        function() {
            defer.resolve()
            console.log(item);
        }, Math.random() * 2000 + 1000);

    return defer.promise();
}