相关疑难解决方法(0)

我必须在何处以及为何要使用"模板"和"typename"关键字?

在模板,在那里,为什么我必须把typenametemplate上依赖的名字呢?究竟什么是依赖名称?我有以下代码:

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)

c++ templates c++-faq dependent-name typename

1061
推荐指数
8
解决办法
15万
查看次数

C++中的继承和模板 - 为什么继承成员不可见?

当模板公开继承自另一个模板时,不是应该可访问的基本公共方法吗?

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)

好吧,海湾合作委员会对此嗤之以鼻......我必须遗漏一些完全明显的东西(大脑融化).救命?

c++ inheritance templates

22
推荐指数
3
解决办法
2万
查看次数

为什么派生类找不到基类的类型别名?

让我们从代码示例开始,因为应该很容易看到发生了什么:

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的别名吗?

c++ c++11

4
推荐指数
1
解决办法
76
查看次数

标签 统计

c++ ×3

templates ×2

c++-faq ×1

c++11 ×1

dependent-name ×1

inheritance ×1

typename ×1