你没有它不能正常工作,对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}
{}
// ...
};
或者使用两步初始化并且abl e明确地通过你的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>();
编译器将需要知道什么'n'事先。如果它只在遥远的未来得到解决,你会如何期望它实例化正确的模板? “不是一个持续的表达”就是你需要从中脱离出来的。简答:你不能。很长的回答就是要知道'Node'在做什么'n'。 – tadman
您不能将'n'传递给您的Node类,因为模板参数不会传递给模板,这是函数参数传递给函数的方式。模板和函数是根本不同的东西。 C++根本不能这样工作。 –
模板仅适用于编译时已知的值。 “树:树”内的'n'不知道直到运行时。因此它不能用于模板。你必须使'Tree'本身成为一个模板并将'n'作为模板参数。 –