【发布时间】:2017-02-21 22:27:51
【问题描述】:
我正在将一个库包装到我的班级设计中。我想在我的类构造函数的库中调用一个带有 unsigned int 非类型参数的模板方法。
#include <iostream>
#include <bar.h> // template header in here
class foo {
foo(unsigned num) {
BAR<num>(); // a template method BAR inside "bar.h"
}
};
当我尝试解决这个问题时,似乎非类型参数是 constexpr。所以上面的代码会产生错误,说明函数调用内部有const错误。
所以我决定将 foo 类设为类模板,并在 foo 的模板实参参数中传递这个无符号的非类型参数。
#include <iostream>
#include <bar.h> // template header in here
template <unsigned num>
class foo {
foo() {
BAR<num>(); // a template method BAR inside "bar.h"
}
};
这似乎运作良好。但是,我想将头文件和源文件分成单独的 .hpp/.cpp 文件。根据this thread,如果我想将模板实现放在 .cpp 源文件中,我必须在 .cpp 文件末尾显式实例化所有可能的模板参数。对于像无符号整数这样的非类型参数,这是否意味着我必须实例化数千个可能的无符号整数才能使模板可用于所有无符号数字对象?感谢您的帮助。
【问题讨论】:
标签: c++ templates constexpr non-type