【发布时间】:2017-02-27 16:59:21
【问题描述】:
这个问题似乎和下面的问题关系很密切,但我还没有完全理解。
- Can the template parameters of a constructor be explicitly specified?
- Template constructor in a class template - how to explicitly specify template argument for the 2nd parameter?
我想要一个模板类,它在构造函数中做一些不平凡的事情,这取决于另一个模板类型。一个最小的例子是这里:
template <typename A>
class Class {
public:
template <typename B>
Class();
private:
int i;
};
template <typename A, typename B>
Class<A>::Class() {
B b;
i = b.get_number();
}
这不能用 GCC 编译:
$ env LC_ALL=C g++ --std=c++11 -c template.cpp
template.cpp:14:1: error: prototype for 'Class<A>::Class()' does not match any in class 'Class<A>'
Class<A>::Class() {
^~~~~~~~
template.cpp:7:5: error: candidate is: template<class A> template<class B> Class<A>::Class()
Class();
^~~~~
使用 Clang 编译会出现其他错误:
$ env LC_ALL=C clang++ --std=c++11 -c template.cpp
template.cpp:13:1: error: too many template parameters in template redeclaration
template <typename A, typename B>
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template.cpp:3:1: note: previous template declaration is here
template <typename A>
^~~~~~~~~~~~~~~~~~~~~
1 error generated.
当我将模板参数B 附加到整个类时,我可以编译它。
template <typename A, typename B>
class Class {
public:
Class();
private:
int i;
};
template <typename A, typename B>
Class<A, B>::Class() {
B b;
i = b.get_number();
}
有什么办法可以控制模板参数B对构造函数的影响?还是我必须将它附加到整个班级?
【问题讨论】:
-
这样一个构造函数的意义何在?你永远不能调用它。
-
@Barry:这是我的后续问题。我在
Class c<B>;收到语法错误。所以我需要注入一些虚拟变量才能正确推断出类型? -
@MartinUeding 在您链接的一个问题中提出并回答了一个问题。