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

无效的模板依赖成员函数模板推导 - 认为我正在尝试使用std :: set

我有一个继承自基类模板的类模板.

基类模板有一个带有成员函数模板的数据成员,我想从我的超类中调用它.

我知道为了消除对成员函数模板的调用的歧义,我必须使用template关键字,我必须this在超类中明确引用.

this->base_member_obj.template member_function<int>();

所有这一切都很好,除了我正在使用的代码库导致导入整个的相当不幸的错误namespace std,并且我试图调用的模板成员函数被调用set.std::set包含在框架中的某个地方,这会导致GCC认为我正在尝试声明std::set而不是调用成员函数set.

GCC 4.7抛出错误无效使用'class std :: set'

请参阅下面的示例以显示错误.如果您注释掉using namespace std代码编译正常.

遗憾的是,我不可能通过整个代码库,删除每个using namespace std调用,并为std命名空间内的任何内容添加前缀std::

还有其他方法吗?

#include <set>
using namespace std; // comment this out to compile fine

struct blah
{
    template<typename T>
    void set()
    { }
};

template<typename T>
struct base
{
    blah b;
};

template<typename T>
struct super : base<super<T>>
{
    void fun()
    { …
Run Code Online (Sandbox Code Playgroud)

c++ templates stl

6
推荐指数
2
解决办法
576
查看次数

尝试从私有实例调用模板方法时编译器错误

(如果你已经知道答案,这个问题只是另一个问题的重复!)

(请注意我的后续问题:如果存在具有相同名称的不相关全局模板函数,为什么不需要模板关键字?)

当我尝试使用这种结构编译模板化的C++代码时,在指定的行中出现编译器错误:

template <int N>
struct A {
    template <int i>
    void f() {};
};

template <int N>
struct B {
    A<N> a;

    B(A<N>& a) : a(a) {}

    void test() {
        a.f<1>();  // does not compile
    }
};

int main() {
    A<2> a;
    a.f<1>();   // works fine
    B<2> b(a);
    b.test();
}
Run Code Online (Sandbox Code Playgroud)

g++ 说:

test2.cpp: In member function ‘void B<N>::test()’:
test2.cpp:14: error: expected primary-expression before ‘)’ token
test2.cpp: In member function ‘void B<N>::test() [with int N = 2]’: …
Run Code Online (Sandbox Code Playgroud)

c++ templates compiler-errors

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