模板 class 专业化函数调用。 C++

Template class specialization function call. C++

考虑这段代码。

template<class T>
class A
{
    public:
      void f(){..}
      void h(){..}
};


template<>
class A<int>
{
    public:
      void f(){// something different..}
      //void h(){..}
};

int main()
{
    A<int> obj;
    obj.h(); // I want to call A<T>::h(), but compiler erred that there is no h function in A<int>
}

这个调用有办法吗??或者一些解决方法?

根据您在专业化中更改了多少东西,您最好只针对 A<int> 专门化 f 而不是专门化整个 class:

template<class T>
class A
{
    public:
      void f(){cout << "standard";}
      void h(){cout << "standard";}
};

template<>
void A<int>::f() {cout << "specialized";}

int main()
{
    A<bool>{}.f(); //outputs standard
    A<int> obj;
    obj.f();       //outputs specialized
    obj.h();       //outputs standard
}

如果您的专业化比这更复杂,您可以将常见行为分解为基础 class 并从中导出 A

A<T> 是一个 class 模板,它引入了一个基于任何类型名称 T 的 classes A 家族。 A<int>A<T> 的显式特化 - 它取代了通用的 class 定义。跟写的没什么两样:

class Aint {
public:
    void f(); 
};

这个特化只有一个成员函数 - f。所以当你尝试这样做时:

A<int> obj;
obj.h();

无法编译,因为 A<int> 没有名为 h 的成员函数。尽管两者都被命名为 A,但 A<int>A<T> 是无关的 - 一个不是另一个的基础 class,并且存在什么函数和成员并不重要一般 A<T> - A<int> 专业化没有它们。

如果 h 很常见,你可以把它移到基数 class:

struct ABase { // or alternatively ABase<T>
    void h();
}

template <typename T>
class A : ABase {
    void f();
};


template <>
class A<int> : ABase {
    void f();
};

这样 A 的所有实例化都会有一个 h()。也就是说,直到有人继续并添加:

template <>
class A<char> // no inheritance
{
    // no h()
};

这段代码对我有用:

template<class T>
class BaseA {
public:
  void f(){...}
  void h(){...}
};

template<class T>
class A : public BaseA<T>
{
};


template<>
class A<int> : public BaseA<int>
{
    public:
      void f(){...}
      //void h(){..}
};

int main()
{
    A<int> obj;
    obj.h(); // I want to call A<T>::h(), but compiler erred that there is no h function in A<int>
}

它声明了一个基础class,由两者继承。