在模板,在那里,为什么我必须把typename和template上依赖的名字呢?究竟什么是依赖名称?我有以下代码:
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) 如果下面的类不是模板,我可以简单地x在derived课堂上.但是,使用下面的代码,我必须使用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) 以下代码不使用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++官方规范中的某些内容,还是仅仅是一个怪癖?
为什么在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) 亲爱的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++ ×5
templates ×3
c++-faq ×2
base-class ×1
empty-class ×1
inheritance ×1
name-lookup ×1
optimization ×1
typename ×1
visual-c++ ×1