C++ - 为模板类专门化成员函数

标签 c++ templates template-specialization

我有一个表示数学 vector 的类模板:

template<class Value_T, unsigned int N>
class VectorT
{
public:

    void Normalize()
    {
        // normalize only double/float vectors here
    }

private:
    // elements in the vector
    value_type elements[N];     

    // the number of elements
    static const size_type size = N;
};

我想对整数类型的 vector 进行特殊处理,因为这种类型的 vector 规范化是不可能的。所以我需要一个单独的(可能是专门化的)Normalize 方法,它依赖于 VectorT 类模板的模板参数 Value_T。

我曾尝试以不同的方式使用模板特化,但没有成功。我是否必须使 Normalize 函数本身成为模板函数?目前它只是一个普通成员方法。

最佳答案

您可以使用标签调度技术解决这个问题:

#include <iostream>
#include <type_traits>

template<class Value_T, unsigned int N>
class VectorT
{
public:
    void Normalize()
    {
        using tag = std::integral_constant<bool
                                         , std::is_same<Value_T, double>::value
                                           || std::is_same<Value_T, float>::value>;  

        // normalize only double/float vectors here
        Normalize(tag());
    }

private:
    void Normalize(std::true_type)
    {
        std::cout << "Normalizing" << std::endl;
    }

    void Normalize(std::false_type)
    {
        std::cout << "Not normalizing" << std::endl;
    }

    // elements in the vector
    Value_T elements[N];     

    // the number of elements
    static const std::size_t size = N;
};

DEMO

关于C++ - 为模板类专门化成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26260774/

相关文章:

c++ - 如何正确设计和实现函数模板特化?

c++ - 发送输入字符串?

c++ - 智能指针和多态

c++ - FindFirstFile、FindNextFile API 是否不可靠?

c++ - 如何将枚举传递给模板参数

c++ - 如何从 lambda 推导出返回类型?

c++ - 不带参数的部分特化函数模板

c++ - decltype(function) 的类型是什么?为什么我不需要 "const"限定符?

c++ - 编译简单类函数的无法解释的错误? C++

c++ - 封装线程会产生问题