c++ - 模板类二重载函数

标签 c++ templates c++11

我创建了一个对象模板类,我希望第二个函数在 T==int 时运行。但我的问题是,在 sec func() 中,我想在对象上运行第一个 func。

我该怎么做?

 template<typename T> Object<T>::func(){

 } 

 template<> Object<int> Object<int>::func(){
        //somecode
        // I want here run the first func() on the object.
 }

谢谢

最佳答案

将接口(interface)与实现分离是一件简单的事情:

template<typename T> Object<T>::func_impl(){
  // Do stuff here
}

template<typename T> Object<T>::func(){
  // all func does is call func_impl
  func_impl<T>();
} 

template<> Object<int> Object<int>::func(){
  // Maybe do some stuff...
  func_impl<int>(); // ... then call your implementation...
  // .. and maybe do some more stuff
}

澄清一下:您所做的不是重载。这称为模板特化。如果您为该类型提供了专门化,则不可能为给定类型实例化通用模板。

关于c++ - 模板类二重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32508330/

相关文章:

C++ : Should we init class from parent or call directly class?

c++ - 如何使用 typdef 名称 C++ typedef 模板类

c++ - 更新 Apple g++/gcc

php - 在 Yii 中获取当前 Controller ID

c++ - std::sort 是否检查 vector 是否已经排序?

c++ - 在C++中初始化参数化类型的数组

c++ - 如何判断路径是文件还是没有提升权限的目录

c++ - std::tmpfile() 没有选择 TMPDIR 位置

c++ - 根据文本动态调整控件大小

c++ - 类型定义非类型模板参数