这个问题在这里已有答案:
我有以下结构:
template<typename T>
struct S {
std::unique_ptr<T> ptr;
};
S<std::string>* s = new S<std::string>();
s->any_method();
如何在operator->
上调用any_method
到ptr
。更确切地说,我想:
表达式s->any_method()
“将被翻译为”s->ptr->any_method()
。
首先,
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();
}
只需返回一个指针。
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;
};