【问题标题】:Using multiple templates with the same class in C++在 C++ 中使用具有相同类的多个模板
【发布时间】:2019-12-01 06:48:05
【问题描述】:

我在 C++ 中有以下代码 -

template <class T>

class TempClass { 

    T value;

public: 
    TempClass(T item) 
    { 
        value = item; 
    } 

    T getValue() 
    { 
        return value; 
    } 
}; 

int main() 
{ 
    TempClass<string>* String =  
      new TempClass<string>("Rin>Sakura");


    cout << "Output Values: " << String->getValue()  
         << "\n"; 

    class TempClass<int>* integer = new TempClass<int>(9); 
    cout << "Output Values: " << integer->getValue(); 
} 

我想做的是使用多个模板和上面的类 TempClass。我知道这样做的一种方法是使用

template <class T1, class T2>

,但如果我这样做,那么类的所有实例都必须有 2 个模板参数。我想做的更像是:

if (flag)
    //initialize an instance of TempClass with one template

    TempClass<string> s("haha");

else
    //initialize an instance of TempClass with 2 templates.

    TempClass<string, int> s("haha", 5);

有没有办法在不使用另一个新类的情况下做到这一点?

【问题讨论】:

    标签: c++ class templates


    【解决方案1】:

    您可以使用可变参数模板和std::tuple 来保存不同类型的值。最小的例子:

    template<class... Ts>
    class TempClass {
        using Tuple = std::tuple<Ts...>;
        Tuple values;
    
    public: 
        TempClass(Ts... items) : values{items...} {} 
    
        template<std::size_t index>
        std::tuple_element_t<index, Tuple> getValue() const {
            return std::get<index>(values);
        } 
    }; 
    
    int main() {
        TempClass<int, std::string, double> tc1{0, "string", 20.19};
        std::cout << tc1.getValue<2>(); // Output: 20.19
    }
    

    std::tuple_element_t 仅从 C++14 开始可用。在 C+11 中,您应该更详细:typename std::tuple_element&lt;index, Tuple&gt;::type

    【讨论】:

    • 是的,您的答案似乎正是我想要的。但是,在this 编译器上运行时,我收到 error: 'tuple_element_t' in namespace'std' does not name a template type 错误。据我所知,这可能是编译器的问题。
    • @RijulGanguly,试试typename std::tuple_element&lt;index, Tuple&gt;::type
    猜你喜欢
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2022-01-15
    • 2011-09-16
    • 1970-01-01
    相关资源
    最近更新 更多