覆盖operator->将方法委托给成员[duplicate]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

我有以下结构:

template<typename T>
struct S {
std::unique_ptr<T> ptr;

};

S<std::string>* s = new S<std::string>();

s->any_method();

如何在operator->上调用any_methodptr。更确切地说,我想:

表达式s->any_method()“将被翻译为”s->ptr->any_method()

c++ c++11 delegates
2个回答
2
投票

首先,

S* s = new S();

是不正确的。 S是一个类模板,而不是一个类。您需要一个模板参数来实例化对象,例如:

S<int>* s = new S<int>();

假设首先修复......

s->any_method()是指针时,你不能使用s

如果你重载s->any_method(),当s是对象或对象的引用时,你可以使用operator->

这是一个最小的例子。

#include <memory>

template<typename T>
struct S {
   std::unique_ptr<T> ptr;
   T* operator->() { return ptr.get(); }
};

struct foo { void any_method() {} };

int main()
{
   S<foo> s;
   s->any_method();
}

0
投票

只需返回一个指针。

template<typename T> struct S {
    S(T &&t): ptr(std::make_unique<T>(std::move(t))) {}
    S(T const &t): ptr(std::make_unique<T>(t)) {}

    T *operator->() { return ptr.get(); }
    std::add_const_t<T> const *operator->() { return ptr.get(); }
private:
    std::unique_ptr<T> ptr;
};
© www.soinside.com 2019 - 2024. All rights reserved.