相关疑难解决方法(0)

获取没有对象的成员函数的返回类型

我有一些我无法修改的课程.每个都有一个复制构造函数,至少一个其他构造函数,以及一个foo()返回一些值的函数.我想创建一个可以从这些类中派生出来的类模板,并且有一个与返回类型相同类型的数据成员foo()(抱歉,如果我的某些术语有误).

换句话说,我想要一个类模板

template<typename T> class C : public T
{
  footype fooresult;
};
Run Code Online (Sandbox Code Playgroud)

footype返回类型在哪里T::foo().

如果基类都有一个默认的构造函数,我可以这样做

decltype(T().foo()) fooresult;
Run Code Online (Sandbox Code Playgroud)

(使用GCC中的C++ 0x功能)但除了复制构造函数之外,这些类没有任何特定的构造函数.

GCC也不允许decltype(this->foo()),虽然显然有可能将其添加到C++ 0x标准 - 有谁知道这有多大可能性?

我觉得应该可以做某些事情decltype(foo())或者decltype(T::foo())那些似乎不起作用的东西:GCC给出了表格的错误cannot call member function 'int A::foo()' without object.

当然,我可以有一个额外的模板参数footype,甚至是类型的非类参数T,但有没有办法避免这种情况?

c++ templates decltype c++11

37
推荐指数
3
解决办法
1万
查看次数

推断成员函数的返回类型

在模板函数我试图创建一个std::vector与它value_type依赖于模板参数的函数的成员函数。该模板参数被限制为包含具有特定功能的特定类型的唯一指针的向量。例如:

/* somewhere in the code */
std::vector< std::unique_ptr< Widget > > myVec;
/* work with myVec and fill it, then call the relevant function */
func(myVec);
Run Code Online (Sandbox Code Playgroud)

现在函数func需要检索的成员函数的返回类型member_funcWidget。请注意,Widget也可以是不同的类型,只要它具有成员函数member_func

template <typename Vec>
void func(const Vec& vec) {
  using ret_type = decltype(Vec::value_type::element_type::member_func()); // Doesn't work
  std::vector< ret_type > local_vec;
}
Run Code Online (Sandbox Code Playgroud)

我尝试了各种方法,例如std::result_of,std::invoke_resultdecltype,但我似乎无法让它工作。这甚至是可能的,如果是,如何实现?

c++ templates result-of decltype

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

标签 统计

c++ ×2

decltype ×2

templates ×2

c++11 ×1

result-of ×1