Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

c++ - 在C ++中对同一类使用多个模板(Using multiple templates with the same class in C++)

I have the following code in C++ -

(我在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()  
         << "
"; 

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

What I would like to do is use multiple templates with the above class TempClass.

(我想做的是在上述类TempClass中使用多个模板。)

I know one way of doing this is by using

(我知道一种方法是使用)

template <class T1, class T2>

, but if I do that then all instances of the class must have 2 template arguments.

(,但是如果我这样做,则该类的所有实例都必须具有2个模板参数。)

What I want to do is something more like :

(我想做的更像是:)

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);

Is there a way to do this without using another new class?

(有没有不用另一个新类就可以做到这一点的方法?)

  ask by Rijul Ganguly translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a variadic template and an std::tuple to hold values of distinct types.

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

Minimal example:

(最小示例:)

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 is available only since C++14.

(std::tuple_element_t仅在C ++ 14起可用。)

In C+11 you should be more verbose: typename std::tuple_element<index, Tuple>::type .

(在C + 11中,您应该更加冗长: typename std::tuple_element<index, Tuple>::type 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...