Ant*_*iro 4 c++ templates compile-time constexpr
大小为“N”的两个向量的标量积定义为 SP(a, b) = a_1 * b_1 + ... + a_N * b_N。
编译时整数向量定义为:
template<int... I>
struct Vector;
Run Code Online (Sandbox Code Playgroud)
功能产品界面:
template<typename Vector1, typename Vector2>
constexpr int product
Run Code Online (Sandbox Code Playgroud)
例如,可以使用以下代码进行测试:
static_assert(product<Vector<1, 2, 5>, Vector<1, 3, 4>> == 27);
Run Code Online (Sandbox Code Playgroud)
如何实现产品才能匹配上面的断言和接口?
使用 C++17 折叠
template <int...>
struct Vector
{ };
template <typename, typename>
constexpr int product = -1;
template <int ... Is, int ... Js>
constexpr int product<Vector<Is...>, Vector<Js...>> = (... + (Is*Js));
int main ()
{
static_assert(product<Vector<1, 2, 5>, Vector<1, 3, 4>> == 27);
}
Run Code Online (Sandbox Code Playgroud)