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

哪个编译器是对的?需要模板化返回类型之前的'模板'吗?

这段代码(取自这个问题)用g ++(如图所示)编译得很好,所以template返回类型就在那之前.相反,VC10不会使用以下错误编译该代码:

错误C2244:'A :: getAttr':无法将函数定义与现有声明匹配

如果我删除了template,VC10很高兴,但g ++尖叫这个错误:

错误:非模板'AttributeType'用作模板
注意:使用'A :: template AttributeType'表示它是模板

是否因为VC的两阶段查找失败或原因是什么?哪个编译器就在这里?我怀疑g ++是正确的,因为我template在这里需要一个模糊的记忆,比如rebind分配器里面的模板.


编辑:我们有一个胜利者:g ++/GCC(惊喜......).


template <typename T, typename K>
class A {
public:
    T t;
    K k;

    template <int i, int unused = 0>
    struct AttributeType{
    };

    template <int i>
    AttributeType<i> getAttr();

};

template <typename T, typename K>
template <int i>
typename A<T, K>::template AttributeType<i> A<T, K>::getAttr() {
//                ^^^^^^^^ -- needed or not?
    return t; …
Run Code Online (Sandbox Code Playgroud)

c++ templates correctness g++ visual-c++

15
推荐指数
1
解决办法
743
查看次数