如何创建抽象数据类型的模板 class?

How to creating a template class that abstracts the data types?

我正在编写一组算法来创建一个简单的单元测试框架。标题为 UnitTest 的 class 使用标题为 strng 的字符串实例化,该字符串描述了正在进行的测试。数据类型也在 object 实例化时传递,这允许编译器知道传递的是什么数据类型。 main.cpp文件和unit_test.hpp文件如下所示

// main.cpp file
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include "unit_test.hpp"

int main(int argc, const char * argv[]) {
    std::vector<int> array_one = {1, 2, 3, 4};
    std::vector<float> array_two = {0.99, 1.99, 2.99, 3.99};

    std::string c ("Vector Test");
    UnitTest<int, float> q(c);
    double unc = 0.1;
    q.vectors_are_close(array_two, array_four, unc);
    return 0;
}

// unit_test.hpp file
#ifndef unit_test_hpp
#define unit_test_hpp
#endif /* unit_test_hpp */
#include <string>
#include <typeinfo>
#include <iostream>
#include <cmath>

template <class type1, class type2> class UnitTest
{
public:
    unsigned long remain;
    std::string str;
    UnitTest(std::string strng) {
        str = strng;
        remain = 50 - str.length();
    };
    void vectors_are_close(std::vector<type1>& i, std::vector<type2>& j, double k);
    // ----------------------------------------------------------------
private:
    void is_close(type1& i, type2& j, double k);
};

template <class type1, class type2> void UnitTest<type1, type2>::
vectors_are_close(std::vector<type1>& i, std::vector<type2>& j, double k)
{
    if (i.size() != j.size()) 
    {
        std::cout << str + std::string(remain, '.') +
            std::string("FAILED") << std::endl;
    }
    else 
    {
        try
        {
            for (int a = 0; a < i.size(); a++) {
                is_close(i[a], j[a], k);
            }
            std::cout << str + std::string(remain, '.') +
                std::string("PASSED") << std::endl;
        }
        catch (const char* msg)
        {
            std::cout << str + std::string(remain, '.') +
                std::string("FAILED") << std::endl;
        }
    }
}

template <class type1, class type2> void UnitTest<type1, type2>::
is_close(type1& i, type2& j, double k)
{
    double percent_diff = abs((j - i) / ((i + j) / 2.0));
    if (percent_diff > k)
    {
        throw "Number not in Tolerance";
    }
}

上面显示的成员函数遍历向量容器,以确保每个 induce 中的数据在一定的公差范围内与第二个向量匹配。虽然编写的代码工作得很好,但它要求用户每次想要使用不同的数据类型进行单元测试时 re-instantiate class。

在这种情况下,class 实例化为 UnitTest<int, float>。但在另一种情况下,它可以用 UnitTest<float, double> 实例化。

这种方法没有错,但是用 UnitTest<> 实例化 class 一次并让 vectors_are_close() 函数接受不同的函数似乎更优雅数据类型。有什么方法可以促进这种行为吗?

如果我理解正确,您不想使用模板参数实例化 class,而只是使用 class 名称 UnitTest 并希望传递成员函数的不同实例,如根据不同的 type1s 和 type2s.

如果是这样,您不需要模板 class 相反,模板成员函数:

class UnitTest 
{
private:
    std::string str;
    unsigned long remain;
public:
    UnitTest(const std::string& strng)
        : str{ strng },
          remain{ 50 - str.size() }
    {}

    template <class type1, class type2>
    void vectors_are_close(const std::vector<type1> &i, const std::vector<type2> &j, double k)
    {
       // code
    }
private:
    template <class type1, class type2>
    void is_close(type1 i, type2 j, double k)
    {
      // code
    }
};

int main() 
{
    std::vector<int> array_one{ 1, 2, 3, 4 };
    std::vector<float> array_two{ 0.99f, 1.99f, 2.99f, 3.99f };
    std::vector<double> array_three{ 0.99, 1.99, 2.99, 3.99 };
    double unc = 0.1;

    UnitTest q{ std::string{"Vector Test"} }; // non-templated class
    // call different types of args to same UnitTest obj
    q.vectors_are_close(array_one, array_two, unc);
    q.vectors_are_close(array_one, array_three, unc);
    return 0;
}

注意:如果您只想为整数和浮点数(或任何特殊类型组)实例化成员函数,请与它们一起使用 SFINAE .

例如,遵循 is_oky_types traits 将允许您仅为对函数体有效的算术类型实例化成员函数。

#include <type_traits>

template<typename Type>
using is_oky_type = std::conjunction<
    std::is_arithmetic<Type>,
    std::negation<std::is_same<Type, bool>>,
    std::negation<std::is_same<Type, char>>,
    std::negation<std::is_same<Type, char16_t>>,
    std::negation<std::is_same<Type, char32_t>>,
    std::negation<std::is_same<Type, wchar_t>> >;

template<typename T, typename U>
using is_oky_types = std::conjunction<is_oky_type<T>, is_oky_type<U>>;

并且在成员函数中:

template <
    class type1,
    class type2,
    std::enable_if_t<is_oky_types<type1, type2>::value>* = nullptr
>
void  vectors_are_close(const std::vector<type1> &i, const std::vector<type2> &j, double k)
{
    // code...
}

template <class type1, class type2>
void is_close(
    type1 i,
    type2 j,
    double k,
    std::enable_if_t<is_oky_types<type1, type2>::value>* = nullptr)
{
    // code...
}