如何在编译时使用externaltemplate参数
How to use externaltemplate parameters in compilation time
我有以下代码:
#include <iostream>
#include <array>
template <class T, size_t dims> class dataType {
public:
void show() {
t_.show();
std::cout << dims << " dimensions" << std::endl;
}
private:
T t_;
};
class heapType {
public:
void show() {
std::cout << "This is heapType class" << std::endl;
}
};
class dataClass {
public:
void show() {
std::cout << "This is dataClass class" << std::endl;
}
};
template < class data_t, class heap_t> class algorithmType {
public:
void showDataType () {
mydata_.show();
}
void showHeapType () {
myheap_.show();
}
void showN() {
std::cout << "I want to use n here" << std::endl;
}
private:
data_t mydata_;
heap_t myheap_;
std::array<int,n> myArray; //Also want to use n here.
};
int main (void) {
constexpr int n = 2;
algorithmType<dataType<dataClass,n>, heapType> myAlgorithm;
myAlgorithm.showDataType();
myAlgorithm.showHeapType();
myAlgorithm.showN();
}
正如预期的那样,输出是:
This is dataClass class
2 dimensions
This is heapType class
I want to use n here
我想在编译时使用algorithmType
中dataType
的dims
模板参数(showN()
方法,主要声明为n
)。真正的代码将根据这个参数执行循环并创建std::数组,所以我希望在编译时知道它,以便编译器进行优化。有可能做到吗?
我对更改类的定义没有任何限制,但我希望它们尽可能接近现在的定义。
谢谢!
编辑:我在algorithmType
私人成员中添加了行std::array<int,n> myArray; //Also want to use n here.
。假设我采用了@kcm1700给出的解决方案,我如何声明数组大小?
你可以做:
template <class T, size_t dims>
class dataType {
public:
constexpr size_t getDims() { return dims; }
...
}
然后像一样使用它
template < class data_t, class heap_t>
class algorithmType {
public:
...
void test() {
int data[mydata_.getDims()];
data[0] = 5;
std::cout << data[0] << std::endl;
}
};
您可以将模板参数用作以下代码。
template <class T, size_t dims> class dataType {
public:
static constexpr size_t n = dims;
...
在showN()中使用它是微不足道的,data_t::n
。
或者,您可以为大小创建一个constexpr函数。
template <class T, size_t dims> class dataType {
public:
constexpr size_t size() const { return dims; }
...
相关文章:
- 没有找到相关文章