本文介绍了c ++类模板专业化,而不必重新实现一切的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板化类,像这样:

  template< typename T& 
class A
{
protected:
std :: vector< T> myVector;

public:
/ *
构造函数+这里的一系列成员函数
* /
}

我想添加只有一个成员函数,它只适用于一个给定类型的T。它是可能做到这一点,而不必专门化该类并重新实现所有其他已有的方法?



感谢

解决方案

p>最简单和最干净的解决方案是在方法的主体中使用 static_assert(),拒绝其他类型(在下面的示例中只接受整数):

  #include< type_traits> 
#include< vector>

template< typename T>
class A
{
public:
void onlyForInts(T t)
{
static_assert(std :: is_same< T,int> :: value ,Works only with ints!);
}

protected:
std :: vector< T> myVector;
};

int main()
{
A< int>一世;
i.onlyForInts(1); // works!

A< float> F;
//f.onlyForInts(3.14f); //不编译!
}




利用这样的事实,即只有当实际使用(而不是类模板本身被实例化)时,编译器实例化类模板的成员函数。对于上面的解决方案,当编译器尝试这样做时,由于执行 static_assert 而失败。



C ++标准参考:




I have a templatized class like so :

template<typename T>
class A
{
    protected:
    std::vector<T> myVector;

    public:
    /*
    constructors + a bunch of member functions here
    */
}

I would like to add just ONE member function that would work only for 1 given type of T. Is it possible to do that at all without having to specialize the class and reimplement all the other already existing methods?

Thanks

解决方案

The simplest and cleanest solution is to use a static_assert() in the body of a method, rejecting other types than the selected one (in the below example only integers are accepted):

#include <type_traits>
#include <vector>

template <typename T>
class A
{
public:
    void onlyForInts(T t)
    {
        static_assert(std::is_same<T, int>::value, "Works only with ints!");
    }

protected:
    std::vector<T> myVector;
};

int main()
{
    A<int> i;
    i.onlyForInts(1); // works !

    A<float> f;
    //f.onlyForInts(3.14f); // does not compile !
}

This utilizes the fact that a compiler instantiates a member function of a class template only when one is actually used (not when the class template is instantiated itself). And with the above solution, when a compiler tries to do so, it fails due to the execution of a static_assert.

C++ Standard Reference:

这篇关于c ++类模板专业化,而不必重新实现一切的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:47