c++ - 将模板类/结构的成员函数地址作为函数参数传递

标签 c++ templates

我的目标是获得自定义容器方法,该方法返回另一个具有相同元素但通过传递转换器成员函数地址转换为不同类型的容器。下面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/

相关文章:

c++ - 为什么在声明 vector 迭代器时使用 typename 关键字?

c++ - 使用 Boost 属性树将 Unicode 字符串写入 XML

c++ - 如何指示容器模板参数的类型?

c++ - c模板成员变量错误

c++ - 模板类型推断可以考虑原始操作类型转换吗?

c++ - while HashMap c++ 的查找函数的条件

c++ - 不能使用一个类的成员 typedef 作为模板特化定义中的模板参数

c# - 生成一个无需C++可再发行组件包即可运行的.exe

c++ - 定义 typedef 的可变参数模板(使用 C++11)

c++ - 具有 C++11 构造的映射函数