相关疑难解决方法(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万
查看次数

在"模板化基类"中调用模板方法时出错

以下代码无法编译,为什么会这样?我该如何解决这个问题?

struct A{
    template<int N> int get() { return N; }
};

template <typename X>
struct B : public X {
    template<int N> int get() {
        return X::get<N>();
    }
};

int main(int argc, const char *argv[])
{
    B<A> b;
    return b.get<5>();
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

test.cxx: In member function ‘int B<X>::get()’:
test.cxx:8:30: error: expected primary-expression before ‘)’ token
test.cxx: In member function ‘int B<X>::get() [with int N = 5, X = A]’:
test.cxx:15:25:   instantiated from here
test.cxx:8:30: error: invalid operands of types …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance templates generic-programming

3
推荐指数
1
解决办法
231
查看次数