c++ - 如何从 C++ 中的现有模板函数定义新函数

标签 c++ templates

最近在学习C++中的模板函数。我想知道是否有任何简单的方法可以让我做以下事情。

例如,我在C++中定义了一个模板函数如下:

template <typename T, float t_p>
void func_a(T* input, T* output):
{
       output = input / t_p;
}

现在,我想基于这个模板函数为 f_p = 4.0 定义另一个模板函数。我知道我可以做以下事情:

template <typename T>
void func_b(T* input, T* output):
{
      func_a<T,4.0>(input, output);
}

但是这段代码看起来很沉重。特别是当我有很多输入变量时。我想知道是否有任何方法可以类似于以下内容

template <typename, T>
func_b = func_a<T , 4.0>;

如果是这样,那将是非常有帮助的

最佳答案

你不能用函数来做,但你可以用仿函数来做。 S.M. 注意到您不能将 float 用作模板非类型参数,因此我们将其替换为 int。我还假设您想对值进行操作,而不是对指针进行操作(取消引用指针或使用引用)。

template<int t_p>
struct func_a
{
    template<typename T>
    void operator()(const T& input, T& output) const
    {
        output = input / t_p;
    }
};

using func_b = func_a<4>;
using func_c = func_a<5>;

现在您可以按以下方式使用这些仿函数:

void foo()
{ 
    int a = 100;
    int b;
    func_a<2>()(a, b);
    func_b()(a, b);
    func_c()(a, b); 
}

请注意,您需要额外的空括号来创建仿函数。

如果你想使用float,你可以这样做:

struct func_a
{
    func_a(float p) : p(p) { }

    template<typename T>
    void operator()(const T& input, T& output) const
    {
        output = input / p;
    }

private:
    const float p;
};

void foo()
{
    const auto func_b = func_a(4);
    const auto func_c = func_a(5);

    float a = 100;
    float b;
    func_a(2)(a, b);
    func_b(a, b);
    func_c(a, b);
}

关于c++ - 如何从 C++ 中的现有模板函数定义新函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51796269/

相关文章:

android - 将wifi SSID与c++中的字符串进行比较

c++ - 警告 : disabled use of C++11 features in Armadillo

c++ - 自动构造函数不适用于 <functional> 对象

c++ - glGenFramebuffers 或 glGenFramebuffersEXT?

Git 标记消息模板?

c++ - C++ 中可以使用模板化文字吗?

c++ - 数据成员 'queryCallback' 不能是成员模板

C++:最常见的漏洞是什么以及如何避免它们?

c++ - 使用模板参数更改类的行为

c++ - 类与其基类之间有哪些可检测到的差异?