是否有某种解决方法来解决auto foo(...) -> decltype(this)的问题?

3
我下一个类想要声明一个返回指向该类型的指针的成员函数,但下面的代码:
template<class Key, int b> class b_plus_tree_inner_node {
  auto split() -> decltype(this) {}
};

给我返回这样的错误

在顶层无效使用 "this"

我能用另一种方式吗?我知道 typedef 的存在,但是可能可以使用 decltype 吗?

编辑:

我想达到以下目标:

b_plus_tree_inner_node<Key, b>* split() {...}

2
你实际想要实现什么? - Xeo
1
如果你想要一个成员函数,为什么要在类外声明它? - R. Martinho Fernandes
@R. Martinho Fernandes,打字错误)) - Yola
我认为在函数的开括号之前,“this”不在作用域内,因此不能成为decltype的一部分。由于“this”是一个伪参数,所以这对我来说似乎是一个疏忽。 - Kaz Dragon
2个回答

5
如果你想要一个成员函数,请在类内部进行声明:

成员 函数在类内部声明:

template<class Key, int b> class b_plus_tree_inner_node {
   b_plus_tree_inner_node* split(){}
   // also valid:
   //b_plus_tree_inner_node<Key, b>* split(){}
};

如果您想要一个非成员函数,请将其制作为模板:
template<class Key, int b>
b_plus_tree_inner_node<Key, b>* split(){}

标准允许您编写auto split() -> decltype(this) {},但GCC 4.6尚不支持它(GCC 4.7的主干支持)。

但问题仍然存在。请看我的“答案”。 - TonyK
3
“你只能在成员函数的主体中使用这个。” - 这并不完全正确。在 "decltype" 中,"this" 也可以用于尾随返回类型。这已经定案于马德里会议,所以他的 GCC 不支持它。 - Johannes Schaub - litb

0

你可能想要这个:

template<class Key, int b> 
class b_plus_tree_inner_node 
{        
     b_plus_tree_inner_node<Key, b> split() 
     { 
          return /*...*/;
     }
};

3
由于注入的类名,无需使用模板参数。 - Xeo
注入的类名。很有趣,我之前不知道这个。我想给它点赞。谢谢。 - Yola

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接