在草案C++ 11标准:N3337中,我发现了几个引用top-level cv-qualifiers,但没有定义.
N3690,§14.8.2第3段有一个非常令人兴奋的例子:
template <class Z> void h(Z, Z*);
// #5: function type is h(int, const int*)
h<const int>(1,0);
Run Code Online (Sandbox Code Playgroud)
问题:为什么不h(const int, const int*)呢?
从什么知道,Z = const int所以Z模板声明中的每个出现都可以被读作const int,或者我错过了什么?为什么指针不同?我记得当参数有T&或T*它保留了cv-qualifiers时T,但我认为没有任何可能在这里应用它.
我想打印类型的名称以进行调试,所以我创建了一个函数来实现这个目的(事实上,我从另一个答案借用了它,我现在找不到),该函数如下所示:
template <typename T> std::string TypeName(T)
{
auto name = typeid(T).name();
int status = 0;
std::unique_ptr<char, void(*)(void*)> res {
abi::__cxa_demangle(name, NULL, NULL, &status),
std::free
};
return ((status == 0) ? res.get() : name);
}
Run Code Online (Sandbox Code Playgroud)
它工作正常:
int i = 0;
float f = 0.f;
std::cout << TypeName(i) << '\n'; // int
std::cout << TypeName(f) << '\n'; // float, so far so good
std::cout << TypeName(&i) << '\n'; // int *
std::cout << TypeName(&f) << '\n'; // float *, as …Run Code Online (Sandbox Code Playgroud) #include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;
class A
{
public:
const shared_ptr<const int> getField () const
{
return field_;
}
private:
shared_ptr<int> field_;
};
void f(const A& a)
{
auto v = a.getField(); //why auto doesn't a const shared_ptr<const int> here ?
v.reset(); //OK: no compile error
}
int main()
{
A a;
f(a);
std::cin.ignore();
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,为什么编译器推断出v的类型shared_ptr<int>而不是const shared_ptr<const int>getField返回的类型?
编辑: MSVC2010
以下有什么区别:
const char *c = 0; //Here c is a pointer to a constant character
typedef char *pstring;
const pstring cstr = 0 //cstr is a constant pointer to a character
Run Code Online (Sandbox Code Playgroud)
为什么这两个语句有区别,但它们看起来一样。在C++ Primer中提到,第一条语句的基类型是const char,*是声明符的一部分。而对于最后一条语句,基本类型是 const pstring。我没有得到两者之间的区别。