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

为什么我必须通过this指针访问模板基类成员?

如果下面的类不是模板,我可以简单地xderived课堂上.但是,使用下面的代码,我必须使用this->x.为什么?

template <typename T>
class base {

protected:
    int x;
};

template <typename T>
class derived : public base<T> {

public:
    int f() { return this->x; }
};

int main() {
    derived<int> d;
    d.f();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ inheritance templates c++-faq

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

GCC问题:使用依赖于模板参数的基类成员

以下代码不使用gcc编译,但使用Visual Studio编译:

template <typename T> class A {
public:
    T foo;
};

template <typename T> class B: public A <T> {
public:
    void bar() { cout << foo << endl; }
};
Run Code Online (Sandbox Code Playgroud)

我收到错误:

test.cpp:在成员函数'void B :: bar()'中:

test.cpp:11:错误:在此范围内未声明'foo'

但它应该是!如果我换bar

void bar() { cout << this->foo << endl; }
Run Code Online (Sandbox Code Playgroud)

然后它确实编译,但我不认为我必须这样做.GCC在这里遵循C++官方规范中的某些内容,还是仅仅是一个怪癖?

c++ templates base-class class-members name-lookup

34
推荐指数
4
解决办法
7135
查看次数

为什么空基类优化不起作用?

为什么在Visual C++中没有完全应用空基类优化(EBO)?

如果我有很多基类,有什么办法让我帮助编译器进行这种优化吗?

#include <iostream>

struct T1 { };
struct T2 { };
struct T3 { };
struct T4 { };
struct T5 { };
struct T6 { };

struct Test : T1, T2, T3, T4, T5, T6 { };

int main() { std::cout << sizeof(Test); }   // Prints 5
Run Code Online (Sandbox Code Playgroud)

c++ optimization visual-c++ empty-class

14
推荐指数
3
解决办法
1600
查看次数

Visual C++〜不内联简单的const函数指针调用

亲爱的StackOverflowers,

我在Microsoft Visual Studio C++ 2012上编写了一段简单的代码:

int add(int x, int y)
{
    return x + y;
}

typedef int (*func_t)(int, int);

class A
{
public:
    const static func_t FP;
};

const func_t A::FP = &add;

int main()
{
 int x = 3;
 int y = 2;
 int z = A::FP(x, y);
 return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器生成以下代码:

int main()
{
000000013FBA2430  sub         rsp,28h  
int x = 3;
int y = 2;
int z = A::FP(x, y);
000000013FBA2434  mov         edx,2  
000000013FBA2439  lea         ecx,[rdx+1] …
Run Code Online (Sandbox Code Playgroud)

c++ function-pointers

9
推荐指数
1
解决办法
1459
查看次数