【问题标题】:How to define a new function from an existed template function in C++如何从 C++ 中的现有模板函数定义新函数
【发布时间】:2018-08-11 03:42:31
【问题描述】:

最近在学习 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>;

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

【问题讨论】:

  • 您确定要将 指针 除以浮点值吗?

标签: c++ templates


【解决方案1】:

你不能用函数来做,但你可以用函子来做。 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);
}

【讨论】:

    【解决方案2】:

    也许有点离题,但我给你一个有用的,我希望的,小建议:切换你的模板参数的顺序。

    我的意思是:写func_a()如下(我使用int作为t_p,因为正如SM所指出的,float值不能是有效的模板参数)

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

    重点是 T 可以从函数参数(inputoutput)推导出来,其中 t_p 无法推导出来,因此必须加以说明。

    如果顺序是T第一和t_p第二,你还必须解释T,所以(通过例子)func_b()你必须写

    func_a<T,4>(input, output);
    

    如果顺序是t_p在前,T在后,你必须只解释t_p,你可以让编译器推导出T类型;所以你可以简单地写

    func_a<4>(input, output);
    

    在这种情况下有一点改进,但​​在其他情况下可能有用。

    【讨论】:

    • 非常感谢。它有一点帮助,但不是太多。确实,我项目中的函数func_a有30多个参数。我的目标是定义一个func_b = func_a,在定义func_b时不写下30个参数名
    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 2015-06-16
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多