【发布时间】:2017-11-04 00:31:18
【问题描述】:
我正在尝试获取我正在编写的一段代码,以便让工作变得有趣。基本上我想生成一个 type,在编译时给出:一个矩阵。
例如,我希望 abstract_matrix 类似于以下内容:
template <std::size_t r, std::size_t c, class T = double>
class abstract_matrix
{
public:
static const std::size_t rows = r;
static const std::size_t cols = c;
typedef T value_type;
typedef T storage_type[rows][cols];
constexpr abstract_matrix(storage_type items)
{
// I hope it's not needed
}
storage_type storage;
};
然后,我想真正创建具有一些魔法的具体类型,如下所示:
constexpr static const int vals[3][3] {
{ 1, 0, 0 },
{ 0, 1, 0 },
{ 0, 0, 1 }
};
// do magic here for the vals parameter to make this compile
using id_3by3 = abstract_matrix<3, 3, vals, int>;
// use the generated type
id_3by3 mymatrix;
auto matrix = mymatrix * ...;
您对如何将这些值“注入”到模板中并在编译时生成正确的类型有什么建议吗?类型中的所有内容都是static、const 和constexpr。
谢谢!
【问题讨论】:
-
您希望矩阵的值成为其类型的一部分?为什么?为什么不简单地
abstract_matrix<3, 3, int> id_3by3(vals);? -
您不想在模板参数列表中传递
vals。看看std::initializer_list。它提出了constexpr的一些问题,尽管它们可能正在修复中。请参阅:stackoverflow.com/questions/15937522/…。 -
是的,您真的不希望元素值成为类型的一部分,因为这将很快导致无法想象的大量模板膨胀,我无缘无故可以想象,或者甚至可能只是在超出某个维度时使编译器崩溃。或许你应该解释一下为什么你认为你想要这个,这样你就可以得到更多有用的答案'不要那样做'。
-
@underscore_d,我怀疑这会导致代码臃肿。并非
vals数组的所有值都成为模板定义的一部分。只有vals的地址成为模板定义的一部分。 -
@RSahu 这对我来说似乎是一个假设,源于问题的模糊性。我的假设恰好不同。