什么是implicit_cast?什么时候我应该更喜欢implicit_cast而不是static_cast?
根据Scott Meyers的说法,为了防止在const版本的getter和非const版本的getter中重复代码,请从非const版本调用该方法的const版本:static_cast<const A&>(*this).Methodology(); 但是,由于过度热心而意外使用我输入的Visual Assist X Intellisense:const_cast<const A&>(*this).Methodology();它运行得很好.
在这种情况下使用特定演员阵容有什么区别?
正在使用的IDE:Visual Studio 2010.
我试图解决一个decltype会大大简化问题的问题,但是我遇到了一个使用decltypeon *this并添加const限定符的问题.下面的示例代码演示了该问题.
#include <iostream>
struct Foo
{
void bar()
{
static_cast<const decltype(*this)&>(*this).bar();
}
void bar() const
{
std::cout << "bar" << std::endl;
}
};
int main(int argc, char* argv[])
{
Foo f;
f.bar(); // calls non-const method
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代码在MSVC2010中编译,但执行会递归,直到发生堆栈溢出.
Ideone报告编译器错误
prog.cpp: In member function 'void Foo::bar()':
prog.cpp:7:38: error: 'const' qualifiers cannot be applied to 'Foo&'
Run Code Online (Sandbox Code Playgroud)
如果我换行
static_cast<const decltype(*this)&>(*this).bar();
Run Code Online (Sandbox Code Playgroud)
至
static_cast<const Foo&>(*this).bar();
Run Code Online (Sandbox Code Playgroud)
它按预期工作.
我是否滥用或误解了decltype?
如果我们有带有通用引用参数的构造函数,如何声明复制构造函数呢?
http://coliru.stacked-crooked.com/a/4e0355d60297db57
struct Record{
template<class ...Refs>
explicit Record(Refs&&... refs){
cout << "param ctr" << endl;
}
Record(const Record& other){ // never called
cout << "copy ctr" << endl;
}
Record(Record&& other){ // never called
cout << "move ctr" << endl;
}
};
int main() {
Record rec("Hello");
Record rec2(rec); // do "param ctr"
return 0;
}
Run Code Online (Sandbox Code Playgroud)
根据std::tuple http://en.cppreference.com/w/cpp/utility/tuple/tuple [查看案例3和8]的构造函数列表,这个问题在标准库中以某种方式解决了......但我无法通过stl的码.
PS问题与构造函数中的C++通用引用和返回值优化(rvo)有些相关
PPS目前,我刚Record(call_constructor, Refs&&... refs)为真正的EXPLICIT调用添加了额外的第一个参数.而且我可以手动检测我们是否只有一个参数,如果是Record,并且重定向调用复制ctr/param ctr,但....我不敢相信没有标准的方法...
c++ ×4
c++11 ×2
static-cast ×2
boost ×1
c++14 ×1
const ×1
const-cast ×1
constructor ×1
decltype ×1
templates ×1