我的目标是获得自定义容器方法,该方法返回另一个具有相同元素但通过传递转换器成员函数地址转换为不同类型的容器。下面int main()中的示例以最简单的方式对其进行了描述。
我的问题是我无法弄清楚此类函数参数的正确声明(如果可能)。
PS:我正在使用MSVC编译器。
template<typename container_type>
struct Container
{
...
template
<typename convert_type = container_type,
typename = std::enable_if<!std::is_fundamental<container_type>::value>::type,
typename = std::enable_if<!std::is_pointer<container_type>::value>::type>
Container<convert_type> apply(convert_type (const container_type::*function)() const) const
// error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
// note: see reference to class template instantiation 'Container<container_type>' being compiled
// error C2091: function returns function
{
Container<convert_type> result();
result.reserve(this->size());
for (const auto& i : *this)
{
result.push_back(i.*function());
}
return result;
}
}
int main()
{
Container<std::string> c = { "a", "b", "c" };
Container<const char*> a = c.apply(&std::string::c_str);
}
最佳答案
要修复丢失的退货类型,您可以使用
Container<convert_type> apply(convert_type (container_type::*function)() const) const
您必须修复语法才能进行函数调用。
result.push_back((i.*function)());
在https://ideone.com/REb7Yu上看到一个更简单的示例来演示该思想。
关于c++ - 将模板类/结构的成员函数地址作为函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59523624/