【问题标题】:Constructor with template arguments带有模板参数的构造函数
【发布时间】:2018-01-23 15:47:26
【问题描述】:

我有一个Dynamic 类,可以存储不同的类型:intdoublestd::vector<int>std::vector<double> 等。我有大约 50 个这样的类型。

我希望我的 Dynamic 类型有一个构造函数,我们提供两个信息:

  • 要存储的类型
  • 用于在 Dynamic 类中构造类型的参数

我很期待这样的东西

const Dynamic x<std::vector<double>>{10};

在适当位置构造一个动态对象,该对象的 std::vector&lt;double&gt; 长度为 10。

PS:我可以用C++11,不能用RTTI

【问题讨论】:

  • 构造函数不能有显式模板参数。为什么你不能使用 RTTI 却不得不做这样的事情?
  • 我不清楚您究竟想要实现什么,但模板化构造函数上的this question 可能是相关的。本质上,你不能为构造函数提供模板参数,它们都必须推导出来。
  • @Passer By:我正在设计一个库,我的一些客户在没有 RTTI 的情况下编译。例如,我需要这样一个 Dynamic 对象来加载 JSON 文件。
  • @François:谢谢。我想我需要忘记这个构造函数。太糟糕了。

标签: c++ c++11 templates constructor


【解决方案1】:

必须推导出构造函数模板参数。它们不能明确提供。您可以通过提供一个类型标记来解决此问题,该标记对所需的模板参数进行编码并将其作为附加的构造函数参数传递。例如:

#include <utility>  // For std::forward

struct foo
{
    // Helper tag type
    template<class T>
    struct type_tag {};

    // The template argument T is deduced from type_tag<T>
    template<class T, class ... Args>
    foo(type_tag<T>, Args&&... p_args)
    {
        T value{ std::forward<Args>(p_args)... };
    }
};

int main()
{
    // Provide a type tag so the template argument can be deduced
    foo bar{ foo::type_tag<int>{}, 5 };
}

【讨论】:

  • 感谢弗朗索瓦
【解决方案2】:

只要您不介意将类型信息放在Dynamic 旁边而不是变量名旁边,您就可以使用可变参数:

#include <iostream>
#include <vector>

template <typename T>
class Dynamic
{
public:
    template <typename... Args>
    Dynamic(Args... args) : data_(args...)
    {
    }

    T data_;
};

int main()
{
    const Dynamic<std::vector<double>> x{10};

    std::cout << x.data_.size() << std::endl;
}

【讨论】:

  • 这违背了拥有动态类型的全部目的
  • @Passer By 您能否详细说明将类型放在变量名左侧而不是右侧有什么不同? OP的原始代码仍然是所有静态类型。
  • OP 似乎想要类似std::variant
猜你喜欢
  • 2015-08-04
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多