c++ - 使用模板应用功能模板

标签 c++ templates c++11 c++14

如果以下示例是 C++,它将包含无意义的乱码,因此我将定义该示例以伪代码编写(因此是正确的)。它强烈暗示了我想用 C++ 做什么。

#include <vector>

template<class T>
void increment(T& x)
{
    ++x;
}

template<template<class> class F>
struct Apply
{
    template<class T>
    void operator()(std::vector<T>& v)
    {
        for (auto& x : v)
            F<T>(x);
    }
};

template<template<class> class F, class T>
void apply(F<T> f, std::vector<T>& v)
{
    for (auto& x : v)
        f(x);
}

int main()
{
    std::vector<int> v{1,2,3};

    // apply increment function to v

    // maybe this?
    Apply<increment> a;
    a(v);

    // hmm... or this?
    apply(increment, v);
}

我不知道如何把它变成 C++ 这样:

  1. increment 是函数而不是函数对象。

  2. increment 的参数由Apply/apply推导或提供。

  3. Apply/apply 不知道名称increment

我可以满足三个中的两个,但我不确定如何同时满足所有三个。我遇到的问题是显然需要使用函数模板作为我的编译器不喜欢的模板模板参数。尽管如此,即使该特定路线是禁区,它似乎也确实有可能发挥作用。

如何实现?

编辑:我讨厌更改问题,但我没有很好地尝试正式陈述需求。假设您是 apply 的作者,但不是 increment 的作者。你被 increment 困住了。

最佳答案

您似乎混淆了函数的类型和函数本身。 写作 Apply<increment>在这种情况下没有意义,因为 increment是函数的名称而不是它的类型。 此外,如果不指定模板类型,就不能使用这样的模板函数。但解决方法是改用通用 lambda。

这是一个工作示例

#include <vector>
#include <iostream>

using std::cout;
using std::vector;

template<class T>
void increment(T& x)
{
    ++x;
}

template<class T>
void print(const T& t) {
    for(auto&& v : t)
        cout << v << " ";
    cout << std::endl;
}

template<typename T, typename F>
void apply(T& container, F function) {
    for(auto& v : container) {
        function(v);
    }
}

int main()
{
    vector<int> v{1,2,3};
    print(v);
    // To retrieve a function pointer you must specify the type
    apply(v, &increment<int>);
    print(v);
    // If your using c++14 you can use a generic lambda
    apply(v, [](auto& t) { increment(t); });
    print(v);
}

关于c++ - 使用模板应用功能模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28781010/

相关文章:

c++ - 有哪些有效使用 Apache XML Security 的优秀 C++ 资源?

Django login_required 通过,但 user.is_authenticated 在模板中失败(??)

templates - Angular2 模板 : how to wrap contents of ngFor with DIV

C++检测类型是否为字符串对象

c++ - 线程上下文的静态存储对象优化

c++ - 在哪里放置全局域特定常量(以及如何放置)?

c++ - 在英特尔 Galileo 上运行 C++

c++ - 一个类型是否应该只 move ,仅仅因为复制可能很昂贵?

c++ - 为什么 std::vector 允许对其包含的类型使用可抛出的移动构造函数?

c++ - 预测迭代器