代码之家  ›  专栏  ›  技术社区  ›  bremen_matt

由模板指定的C++类成员

c++
  •  2
  • bremen_matt  · 技术社区  · 7 年前

    是否可以使用变量模板指定类的成员?一个可接受的解决方案是将数据内部存储在一个元组中。

    template <typename ... Args> 
    struct FromPP {
         // TODO: Get the tuple type from parameter pack
         std::tuple<> data;    
         // TODO: write the constructors
    
         // Other code... E.g. A print method, and manipulations with 
         // other points of the same type... 
    }
    

    理想情况下,我想要一些同时具有默认和复制构造函数的实现:

    FromPP<float>();    // decltype(data) == std::tuple<float>
    FromPP<float>(1.1); // decltype(data) == std::tuple<float>
    
    FromPP<float,int>();       // decltype(data) == std::tuple<float,int>
    FromPP<float,int>(1.1, 5); // decltype(data) == std::tuple<float,int>
    

    等。

    如果可能的话,我想要一个C++ 11的解决方案。我们使用的一些硬件有Stc+C++ 14的支持。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Daniel Langr    7 年前

    如果您对元组没问题,那么可以按如下方式定义结构:

    template <typename... Args> 
    struct FromPP {
       std::tuple<Args...> data;    
    
       FromPP() = default;
       FromPP(Args&&... args) : data(std::forward<Args>(args)...) { }
    };
    

    它与您的示例代码一起工作: https://wandbox.org/permlink/163TwS1SrKULgfIH

    这是你想要的吗?