c++ - 通过具有可变参数列表的函数计算欧氏距离

标签 c++ c++11

此示例展示了如何使用可变参数模板来计算平方距离。 不幸的是,如果我想计算欧氏距离,这将不适用于 sqrt() 。 我如何使用可变数量的函数参数计算欧氏距离。

    /*
     * Calculated the euclidian distance of the obtained parameter list
     */
    template<class T>
    T squared_distance(const T &val) {
        static_assert(std::is_floating_point<T>::value || std::is_integral<T>::value, 
            "ERROR - squared_distance(): template parameter not of type integer or float\n");

        return std::pow(val, 2);
    }

    template<class T, class... Params> 
    T squared_distance(const T &first, const Params&... parameters) {
        return std::pow(first, 2) + squared_distance(parameters...);
    }

最佳答案

下面的代码工作得很好:

#include <cmath>
#include <iostream>

/*
 * Calculated the euclidian distance of the obtained parameter list
*/
template<class T>
T squared_distance(const T &val) {
    static_assert(std::is_floating_point<T>::value || std::is_integral<T>::value,
                  "ERROR - squared_distance(): template parameter not of type integer or float\n");

    return std::pow(val, 2);
}

template<class T, class... Params>
T squared_distance(const T &first, const Params&... parameters) {
    return std::pow(first, 2) + squared_distance(parameters...);
}

template<class... Params>
double euclidian_distance(const Params&... parameters)
{
    return std::sqrt(squared_distance(parameters...));
}

int main()
{
    std::cout << euclidian_distance(1, 1, 1);
}

Live on Coliru

顺便说一句,您正在计算(平方)范数,而不是距离,因为距离(通常)是范数的差异。

关于c++ - 通过具有可变参数列表的函数计算欧氏距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34592728/

相关文章:

c++ - 替代 vector <bool>

c++ - 将 lambda 作为参数传递 - 通过引用或值?

c++ - 全局分配函数和 const void*

c++ - 为什么我的程序在分配更多线程的情况下执行时间更长?

c++ - 什么是 “exception vomiting” ?

c++ - 为什么 `std::stringstream::stringstream(std::string&&)` 不存在?

c++ - 如何区分 unsigned int 和 uint32_t

c++ - 删除copy-ctor和copy-assignment - public、private还是protected?

c++ - 错误 "C++ requires a type specifier for all declarations"

c++ - 使用 Qt 和 C++ 创建 SNMP 代理