我正在阅读,我看到以下代码:
template <>
inline bool is_empty(const char* const& x)
{
return x==0 || *x==0;
}
Run Code Online (Sandbox Code Playgroud)
什么const char* const& x意思?
我尝试了以下代码来理解它:
void f(const char* const& x)
{
// whatever
}
void main()
{
char a = 'z';
char &j = a;
f(a);//error
f(*a);//error
f(&a);//fine
f(j);//error
f(&j);//fine
f('z');//error
}
Run Code Online (Sandbox Code Playgroud)
它仅适用于f(&a)和f(&j).
究竟const char* const& x是什么意思?
考虑以下代码:
struct X
{
template <typename T>
class Y
{};
};
template<>
class X::Y<double>{
};
Run Code Online (Sandbox Code Playgroud)
在这里,我们将 Y 类专门用于 double 类型,并且代码运行良好。问题是,如果我将代码更改为:
template<typename A>
struct X
{
template <typename T>
class Y
{};
};
template<typename A>
class X<A>::Y<double>{
};
Run Code Online (Sandbox Code Playgroud)
编译器会报错:
'X::Y':显式专业化正在使用部分专业化语法,请使用模板 <> 代替!
有人知道在这种情况下我该如何专业化 Y 类吗?
我只是想知道std :: identity的目的是什么?我在网上找不到任何有用的东西.我知道它是如何实现的:
template <typename T>
struct identity
{
T operator()(T x) const { return x; }
};
Run Code Online (Sandbox Code Playgroud)
为什么我们真的需要这个呢?
考虑以下代码:
struct A {
virtual void foo() {}
virtual ~A() = 0;
};
struct B :public A
{
virtual void foo() {};
};
A::~A() {};
int main()
{
A * a = new B();
a->foo();
}
Run Code Online (Sandbox Code Playgroud)
它工作得很好.但现在考虑我们需要在函数内部声明我们的类的第二个代码:
void foo()
{
struct A {
virtual void foo() {}
virtual ~A() = 0;
};
struct B :public A
{
virtual void foo() {};
};
A::~A() {}; //error C2352 : 'A::~A' : illegal call of non - static member function
A * a …Run Code Online (Sandbox Code Playgroud) 我正在读"经典C++中的Advance Metaprogramming"一书!在第16页上,作者提供了一个例子:
struct base
{
base() {}
template <typename T>
base(T x) {}
};
struct derived : base
{
derived() {}
derived(const derived& that)
: base(that) {}
};
void main()
{
derived d1;
derived d2 = d1; //stack overflow!! why?!
}
Run Code Online (Sandbox Code Playgroud)
作者说:"赋值d2 = d1导致堆栈溢出.隐式复制构造函数必须调用基类的复制构造函数,因此通过上面的12.8(C++标准)它永远不能调用通用构造函数.编译器生成了派生的拷贝构造函数,它会调用基本拷贝构造函数(它是隐式的).不幸的是,给出了派生的拷贝构造函数,它包含一个显式函数调用,即base(that).因此,遵循通常的重载解析规则,它匹配通用构造函数与T = derived.由于此函数采用x的值,它需要执行该副本,因此调用是递归的."
我真的没有得到它!有人可以解释一下这个!
非常感谢!:)
stack-overflow inheritance copy-constructor template-meta-programming c++11
请参阅以下代码:
#include <iostream>
using namespace std;
struct T
{
~T()
{
cout << "deconstructor calling\n";
}
};
static T& get1()
{
static T x;
return x;
}
static T& get2()
{
static T& x = *new T;
return x;
}
int main()
{
get1();//calls the deconstructor
get2(); //dosent call the deconstructor
}
Run Code Online (Sandbox Code Playgroud)
为什么get1叫解构主义但get2不是?据我所知,当你终止程序时,静态变量会被破坏!但为什么在调用get1程序后调用静态变量的解构?
我有一个类似帖子的阅读:
有人说:"函数静态变量的生命周期首次开始[0]程序流遇到声明,它在程序终止时结束."
这似乎不是真的!
看到这个非常简单的代码:
struct A
{
bool operator ==(const int &t)
{
return *this == t;
}
};
void main()
{
A p;
p == 2;// this code loops for ever!!!
}
Run Code Online (Sandbox Code Playgroud)
剂量任何人都知道为什么代码循环永远?!实际上,运算符==()递归调用自身!
非常感谢