在模板,在那里,为什么我必须把typename和template上依赖的名字呢?究竟什么是依赖名称?我有以下代码:
template <typename T, typename Tail> // Tail will be a UnionNode too.
struct UnionNode : public Tail {
// ...
template<typename U> struct inUnion {
// Q: where to add typename/template here?
typedef Tail::inUnion<U> dummy;
};
template< > struct inUnion<T> {
};
};
template <typename T> // For the last node Tn.
struct UnionNode<T, void> {
// ...
template<typename U> struct inUnion {
char fail[ -2 + (sizeof(U)%2) ]; // Cannot be instantiated for any …Run Code Online (Sandbox Code Playgroud) 当模板公开继承自另一个模板时,不是应该可访问的基本公共方法吗?
template <int a>
class Test {
public:
Test() {}
int MyMethod1() { return a; }
};
template <int b>
class Another : public Test<b>
{
public:
Another() {}
void MyMethod2() {
MyMethod1();
}
};
int main()
{
Another<5> a;
a.MyMethod1();
a.MyMethod2();
}
Run Code Online (Sandbox Code Playgroud)
好吧,海湾合作委员会对此嗤之以鼻......我必须遗漏一些完全明显的东西(大脑融化).救命?
让我们从代码示例开始,因为应该很容易看到发生了什么:
template <typename T>
struct Base
{
using Type = int;
};
template<typename T>
struct Derived : public Base<T>
{
// error: unknown type name 'Type'
using NewType = Type;
};
int main()
{}
Run Code Online (Sandbox Code Playgroud)
我本来希望可以找到Base的Type别名。但是,我尝试过的所有编译器(MSVC,Clang和GCC)似乎都不喜欢此代码。
更令人惊讶的是,将Derived的继承更改为:
struct Derived : public Base<int>
Run Code Online (Sandbox Code Playgroud)
解决问题。
我可以更改一些内容以允许“派生”找到Base的别名吗?