gpt4 book ai didi

c++ - 需要从 C++ 模板函数返回与此相同的类型

转载 作者:行者123 更新时间:2023-11-30 00:45:19 27 4
gpt4 key购买 nike

我想要一个模板函数返回与 this 相同的类型。在parens中获取参数类型很容易,但我不知道如何获取调用其方法的对象的类型。

struct ENode {
ENode* mnext;
ENode(ENode* n):mnext(n){}
template<typename T>T* next(T* unused) { return (T*)mnext; }
template<typename T>T* xnext() { return (T*)mnext; }
};

struct TNode : public ENode {
int val;
TNode(int v, TNode* n):val(v),ENode(n){}
};

void printTN(TNode* n) {
while(n) {
printf("%i -> ", n->val);
// n=n->next(n); // ok, but n is unused
// n=n->xnext(); // error: template argument deduction/substitution failed: couldn't deduce template parameter ‘T’
// n=n->xnext<std::remove_reference<decltype(*n)>::type>(); // works, but is very ugly
n=n->xnext<TNode>(); // works, but is ugly
}
printf("nil\n");
}

如何让 n->next() 返回与 n 相同的类型?

编辑至于 Template deduction for function based on its return type? ,如果可能的话,它会对我有帮助。但是 C++ 中的返回类型没有重载或类型推导(与 Java 不同)。因此,我想要重载 *this 的类型。

最佳答案

一种常见的模式是让整个 ENode 类采用模板参数,而不仅仅是 next/xnext 方法。

例如,

template <typename T> struct ENode {
...
T* next() { return mnext; }
};
struct TNode : ENode<TNode> { ... }

关于c++ - 需要从 C++ 模板函数返回与此相同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43746508/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com