【问题标题】:C++ how to call templated constructor [duplicate]C ++如何调用模板化构造函数[重复]
【发布时间】:2013-04-21 00:10:50
【问题描述】:

如何更改以下代码以允许创建 Base 对象 使用模板化构造函数?

struct Base {
template <typename T>
Base(int a) {}
};

 int main(int argc, char const *argv[])
{
    Base *b = new Base<char>(2);
    delete b;
    return 0;
}

【问题讨论】:

    标签: c++ templates constructor


    【解决方案1】:

    这个帖子似乎回答了你的问题:

    C++ template constructor

    底线是它似乎不受支持;目前还不清楚它会实现什么。

    【讨论】:

    • 有时构造函数处理许多类型,但数据只是临时使用,因此将类本身模板化是多余的。我猜对它的需求不是很大,但这是有道理的。
    【解决方案2】:

    这个问题有点含糊。您是否打算用“T a”替换 Base ctor 中的“int a”?如果是这样,您可能希望使用函数模板类型推断,如下所示:

    template<typename T>
    Base<T> CreateBase(T a)
    {
      return new Base<T>(a);
    }
    
    // Call site avoids template clutter
    auto base = CreateBase(2);
    

    【讨论】:

      猜你喜欢
      • 2011-05-24
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      相关资源
      最近更新 更多