簡體   English   中英

傳遞變量作為模板參數

[英]passing a variable as template argument

我有一個采用整數參數的模板節點類。 我還有一個樹類,它創建一個節點並將其構造函數參數作為節點模板的參數傳遞。

Tree.cpp

Tree::Tree(int n) {
    this->n = n;
    root = new Node<n>(); // compiler error
}

main.cpp中

Tree *tree = new Tree(2);

我的編譯器抱怨'n'不是常量表達式 如何成功將n傳遞給我的節點類?

我認為你不能這樣做。

n在編譯時是已知的,但它不是一個模板參數。 由於在Tree構造函數中需要n ,因此您也可以將Tree類作為模板。

使您的構造函數成為模板之一:

struct Base
{

};
template <int N>
struct Node : Base
{

};

class Tree 
{
public:

    template <int N>
    struct size
    {
    };

    template<int N> Tree(size<N>) {
        this->n = N;
        root = new Node<N>();
    }

    int n;
    Base* root;
};

int main() {

    Tree t = Tree(Tree::size<2>());

    return 0;
}

你這樣做的方式無法工作,因為n必須在編譯時才知道。
您可以使其成為構造函數模板參數。 不幸的是,在這種情況下,它不能明確給出,必須是可推導的。 無論如何,這都是一個丑陋的語法問題。
它遵循一個最小的工作示例:

#include<type_traits>

struct BaseNode {};

template<int n>
struct Node: BaseNode {};

struct Tree {
    template<int n>
    Tree(std::integral_constant<int, n>)
        : n{n}, root{new Node<n>()}
    {}

    int n;
    BaseNode *root;
};

int main() {
    Tree tree{std::integral_constant<int, 2>{}};
}

請注意,您可以使用工廠方法輕松解決難看的語法:

struct Tree {
    template<int n>
    Tree(std::integral_constant<int, n>)
        : n{n}, root{new Node<n>()}
    {}

    template<int n>
    static Tree create() {
        return Tree{std::integral_constant<int, n>{}};
    }

    int n;
    BaseNode *root;
};

// ...

Tree tree = Tree::create<2>();

另一種可能的解決方案是提供一個Node作為參數並從中推導出n

struct Tree {
    template<int n>
    Tree(Node<n> *node)
        : n{n}, root{node}
    {}

    // ...
};

或者使用兩步初始化,並能夠顯式傳遞您的n作為模板參數:

struct Tree {
    Tree(): n{0}, root{nullptr} {}

    template<int n>
    void init() {
        this->n = n;
        root = Node<n>;
    }

    int n;
    BaseNode *root;
};

// ...

Tree tree{};
tree.init<2>();

暫無
暫無

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

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