小编Sim*_*onD的帖子

将STL容器<T*>转换为容器<T const*>

我正在寻找一种方法来制定一个类:

  • 一个接口,使用最大'constness'的指针STL容器
  • 但是它在内部突变了指向的对象
  • 与非const模拟相比,没有额外的运行时开销

理想情况下,与非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)

c++ stl

5
推荐指数
1
解决办法
250
查看次数

通过成员函数指向虚函数调用基本成员函数实现

我有一种情况,我想要一个成员函数指针指向虚拟函数,避免动态调度.见下文:

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)

c++ member-function-pointers

5
推荐指数
1
解决办法
247
查看次数

标签 统计

c++ ×2

member-function-pointers ×1

stl ×1