【发布时间】:2022-01-02 02:47:35
【问题描述】:
我想定义类似于幂函数a^n的模板
-
a^n = -1其中a < 0或n < 0 -
a^0 = 0(所以不完全是std::pow) - 否则
std::pow
我在定义第 1 点的条件时遇到问题 - 我假设这将是 enable_if 和一些定义的 constexpr 检查整数是否为负的组合。
我为 1. 写的内容(在下面注释掉)可能没有意义,因为它无法编译。我只是从元编程开始,说实话我不太了解它。如果您能提供解释和/或一些您在进入该主题时发现有帮助的资源,我将不胜感激。
#include <iostream>
#include <cmath>
// std::pow
template <int a, int n>
struct hc {
enum { v = a * hc<a, n - 1>::v };
};
// to break recursion from getting to a^0=0
template <int a>
struct hc<a, 1> {
enum { v = a };
};
// a^0 = 0
template <int a>
struct hc<a, 0> {
enum { v = 0 };
};
// a^n=-1 for negative a or n
/*
template <int i>
constexpr bool is_negative = i < 0;
// a ^ n = -1, where a < 0 or n < 0
template <int a, int n,
typename std::enable_if<is_negative<a> || is_negative<n>>::type>
struct hc {
enum { v = -1 };
};
*/
int main() {
// a^0=0
std::cout << hc<0, 0>::v << " -> 0^0=0\n";
std::cout << hc<3, 0>::v << " -> 3^0=0\n";
// a^n=std::pow
std::cout << hc<1, 1>::v << " -> 1^1=" << std::pow(1, 1) << '\n';
std::cout << hc<2, 2>::v << " -> 2^2=" << std::pow(2, 2) << '\n';
std::cout << hc<0, 2>::v << " -> 0^2=" << std::pow(0, 2) << '\n';
std::cout << hc<3, 2>::v << " -> 3^2=" << std::pow(3, 2) << '\n';
std::cout << hc<3, 7>::v << " -> 3^7=" << std::pow(3, 7) << '\n';
// a^n=-1 for negative a or n
std::cout << hc<-3, 7>::v << " -> -3^7=-1\n";
std::cout << hc<3, -7>::v << " -> 3^-7=-1\n";
std::cout << hc<0, -7>::v << " -> 0^7=-1\n";
std::cout << hc<-3, 0>::v << " -> -3^0=-1\n";
}
【问题讨论】:
-
你能接触到 C++20 和概念吗?
-
我使用的是 C++14
标签: c++ templates metaprogramming