我正在寻找一种方法来制定一个类:
理想情况下,与非const版本相比,解决方案将编译为无额外代码,因为const/non-const-ness只是对程序员的帮助.
这是我到目前为止所尝试的:
#include <list>
#include <algorithm>
using namespace std;
typedef int T;
class C
{
public:
// Elements pointed to are mutable, list is not, 'this' is not - compiles OK
list<T *> const & get_t_list() const { return t_list_; }
// Neither elements nor list nor' this' are mutable - doesn't compile
list<T const *> const & get_t_list2() const { return t_list_; }
// Sanity check: T const * is the problem - doesn't compile …Run Code Online (Sandbox Code Playgroud) 我有一种情况,我想要一个成员函数指针指向虚拟函数,避免动态调度.见下文:
struct Base
{
virtual int Foo() { return -1; }
};
struct Derived : public Base
{
virtual int Foo() { return -2; }
};
int main()
{
Base *x = new Derived;
// Dynamic dispatch goes to most derived class' implementation
std::cout << x->Foo() << std::endl; // Outputs -2
// Or I can force calling of the base-class implementation:
std::cout << x->Base::Foo() << std::endl; // Outputs -1
// Through a Base function pointer, I also get dynamic dispatch …Run Code Online (Sandbox Code Playgroud)