簡體   English   中英

如何在 c++ 中聲明一個相同的 class 但具有不同模板參數的新變量?

[英]How can I declare a new variable of the same class but with different template parameters in c++?

我想編寫一個模板 function,給定任何 class,將實例化一個新模板,但模板參數為 1。我想做這樣的事情:

template <uint COUNT>
class Foo {
    using MY_NAME = Foo;
    int data[COUNT];
    void print();
}

template <class T>
void my_function(T in) {
    auto x = in::MY_NAME<1>;  // This somehow makes a XXX<whatever> into an XXX<1>.
    x.print();
}

my_function(Foo<5>); // This should call Foo<1>.print();

我想使用模板或using或其他東西,以便無論我收到什么輸入 class,我都會創建一個與 class 相同但具有不同模板參數的新實例。

這可以做到嗎? 這一切在編譯時都是已知的,所以似乎應該有一種方法可以做到這一點。

使用模板模板參數 在這種情況下,您可能希望為內部模板指定一個非類型模板參數。 那看起來像

template <std::size_t COUNT>
struct Foo {
    using MY_NAME = Foo;
    int data[COUNT];
    void print() { std::cout << "COUNT: " << COUNT; }
};

template <template<std::size_t> typename class_t, std::size_t N>
void my_function(class_t<N>) {
    auto x = class_t<1>{};  // This somehow makes a XXX<whatever> into an XXX<1>.
    x.print();
}

int main()
{
    my_function(Foo<5>{}); // This should call Foo<1>.print();
}

它輸出

COUNT: 1

如本實例所示

我不確定是否可以讓 using 聲明做你想做的事,讓MY_NAME引用注入的模板名稱Foo而不是注入的 class 名稱Foo<COUNT> 但是你可以讓MY_NAME本身成為一個模板:

#include <iostream>

template <uint COUNT>
class Foo {
public:
    template<uint C>
    using MY_NAME = Foo<C>;
    
    int data[COUNT];
    void print() { std::cout << COUNT << '\n'; }
};

template <class T>
void my_function(T in) {
    auto x = typename T::MY_NAME<1>{};  // Typename keyword is necessary here
    x.print();
}

int main()
{
    my_function(Foo<5>{}); // Prints 1
    my_function(Foo<7>{}); // Prints 1
}

演示在這里

因此,現在對於任何通過using MY_NAME導出其名稱的 class 模板Bar ,您可以將其傳遞給my_function以調用Bar<1>.print()

不確定你需要它做什么,但你正在尋找的語法可能是這樣的:

#include <array>
#include <iostream>
#include <utility>

template<std::size_t N>
struct Foo
{
    // initialized array
    std::array<int,N> data {};

    // output all the values in the array
    void print()
    {
        for (const int value : data) std::cout << value << " ";
    }
};

template<typename type_t>
void my_function(const type_t& value)
{
    std::cout << "my_function(" << value << ")\n";
    // create a temporary and print it.
    Foo<1>().print();
}

int main()
{
    int v{ 5 };
    my_function<int>(v);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM