小编Tel*_*oze的帖子

类模板的成员函数模板的显式实例化

假设我的头文件中有一个带有成员函数模板的类模板。

//file.hxx
template<class T>
struct A {
    T val;
    template<class U> foo(U a);
};
Run Code Online (Sandbox Code Playgroud)

我在 .cpp 中有 foo 的实现:

//file.cpp
#include "file.hxx"
#include <typeinfo>
template<class T> template<class U>
A<T>::foo<U>(U a){
    std::cout << "Type T: " << typeid(val).name() << std::endl;
    std::cout << "Type U: " << typeid(a).name() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

如果我想在 .cpp 文件中显式实例化我的类和成员函数(例如 int 和 float),我需要类似以下内容:

template struct A<int>;
template struct A<float>;
template A<int>::foo<int>(int);
template A<int>::foo<float>(float);
template A<float>::foo<int>(int);
template A<float>::foo<float>(float);
Run Code Online (Sandbox Code Playgroud)

如果我开始有很多类型的 T 和 U,这会变得有点冗长。有没有更快的方法可以做到这一点,并且仍然在 cpp 文件中显式实例化模板?我在想象类似的事情

template<class T>
template A<T>::foo<int>(int);
template<class …
Run Code Online (Sandbox Code Playgroud)

c++ templates explicit-instantiation

7
推荐指数
0
解决办法
3014
查看次数

派生类中的“重命名”成员变量

这个问题似乎有点怪异,但我将尝试对用例进行一点争议。

假设您有一个二维(笛卡尔)字段的通用实现,该字段的尺寸为dim1和dim2,坐标为c1和c2。

struct Field2D {
  struct size_type {
     size_t dim1,dim2;
  };
  struct coordinates {
     size_t c1,c2;
  }
Field2D(size_type const & siz) : size_(siz), data(size_.dim1*size_.dim2) {}
double get(coordinates const & coords) {
  return data_[coords.c1*size_.dim2 + coords.c2];
}
//Other methods
private:
  size_type size_;
  vector<double> data_;
};

Run Code Online (Sandbox Code Playgroud)

您想从此类继承,但您想更明确地了解坐标的性质。例如,一个字段PositionVersusTime,其坐标为“ x”和“ t”,尺寸为“ nx”和“ nt”,我想将其用法

int main(){
   PositionVersusTime::size_type siz;
   siz.nx = 5;
   siz.nt = 2;
   PositionVersusTime myField(siz);
   PositionVersusTime::coordinates coords;
   coords.x = 2;
   coords.t = 0;
   auto out = myField.get(coords);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我要执行此操作的原因是,排序可能会根据字段(例如TimeVersusPosition)而改变,有时会被用户“遗忘”。有没有办法获得类似的行为?还是我应该简单地使用吸气剂(例如,coords.x()= 2)?

c++ member-variables

5
推荐指数
2
解决办法
113
查看次数