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

3

我正在编写一组算法来创建一个简单的单元测试框架。类 UnitTest 被实例化为一个字符串 strng,该字符串描述了所进行的测试。数据类型在对象实例化时也被传递,这使得编译器知道正在传递哪些数据类型。下面是 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";
    }
}

上面展示的成员函数遍历向量容器,以确保每个感应器中的数据与第二个向量在一定公差范围内匹配。虽然代码按照原样工作得很好,但它要求用户每次想用不同的数据类型进行单元测试时重新实例化类。
在这种情况下,该类使用UnitTest<int, float>进行实例化。但在另一个实例中,它可能使用UnitTest<float, double>进行实例化。
这种方法没有问题,但似乎更优雅的方式是只用UnitTest<>实例化一次类,然后使vectors_are_close()函数接受不同的数据类型。是否有某种方法可以促进这种行为?
1个回答

5
如果我理解的正确,你不想使用模板参数来实例化类,而是只想使用类名UnitTest,并希望根据不同的type1和type2传递不同的成员函数实例。
如果是这样,你不需要一个模板类,而是需要模板成员函数
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...
}

1
谢谢,由于某些原因,我认为您不能在非模板类中实例化模板函数,但现在我看到这是因为我没有在函数中声明类类型,而只在原型中声明了。不久我将提出另一个相关问题。 - Jon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接