【发布时间】:2016-02-17 16:56:34
【问题描述】:
我需要使模板类构造函数采用依赖类型(在模板类类型上)。这很好用,除非我有模板类的专门化,在这种情况下似乎找不到构造函数。而且如果我在专门的子类中重新实现构造函数,我似乎无法通过构造函数或直接初始化基类。
有没有办法在类之外保留这个相对狭窄的接口?
class T1 {};
class T2 {};
// KeyType
template <typename SELECT>
class KeyType {
};
// Declarations
template <typename SELECT = T1>
class TestTemplate {
protected:
TestTemplate() {}
KeyType<SELECT> k;
public:
TestTemplate(KeyType<SELECT> const &key) : k(key) {}
};
template <>
class TestTemplate<T2> : public TestTemplate<T1> {
};
int main() {
KeyType<T2> key;
TestTemplate<T2> foo(key);
return 0;
}
看了一会儿,我意识到问题是我不能随意将KeyType<T2> 转换为KeyType<T1> 用于TestTemplate<T1> 基类。
g++ 给出:
g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In function 'int main()':
main.cpp:27:29: error: no matching function for call to 'TestTemplate<T2>::TestTemplate(KeyType<T2>&)'
TestTemplate<T2> foo(key);
^
main.cpp:20:7: note: candidate: TestTemplate<T2>::TestTemplate()
class TestTemplate<T2> : public TestTemplate<T1> {
^
main.cpp:20:7: note: candidate expects 0 arguments, 1 provided
main.cpp:20:7: note: candidate: constexpr TestTemplate<T2>::TestTemplate(const TestTemplate<T2>&)
main.cpp:20:7: note: no known conversion for argument 1 from 'KeyType<T2>' to 'const TestTemplate<T2>&'
main.cpp:20:7: note: candidate: constexpr TestTemplate<T2>::TestTemplate(TestTemplate<T2>&&)
main.cpp:20:7: note: no known conversion for argument 1 from 'KeyType<T2>' to 'TestTemplate<T2>&&'
【问题讨论】:
-
如果您将
TestTemplate<T2>特化为从TestTemplate<T1>继承,那么将KeyType<T2>特化为从KeyType<T1>继承可能也是有意义的。这将解决问题。 -
@StenSoft 我觉得不对,
TestTemplate<T2>没有接受KeyType<T1> const&的构造函数。