template<int... I>
struct with
{
template<int F(decltype(I)...)>
struct call
{
static constexpr int value = F(I...);
};
};
constexpr int f(int i) {return i;}
constexpr int g(int i, int j) {return i + j;}
int main()
{
int u = with<0>::call<f>::value;
constexpr int v = with<0, 1>::call<g>::value;
}
请注意,这有一些限制,就像我回答的上一个问题一样。但是在编译时仍然可以从非类型模板参数生成一个值。std::integral_constant
constexpr
double
#include <iostream>
template<typename T, T... v>
struct with
{
template<typename R, R f(decltype(v)...)>
struct call
{
static constexpr R value = f(v...);
};
};
#define AT_COMPILATION(f, x, ...) with<decltype(x), x, ##__VA_ARGS__>::call<decltype(f(x, ##__VA_ARGS__)), f>::value
constexpr long f(long i) {return i;}
constexpr double g(int i, int j) {return static_cast<double>(i) / j;}
int main()
{
constexpr double u = with<long, 0L>::call<decltype(f(0L)), f>::value;
std::cout << with<int, 5, 2>::call<double, g>::value << std::endl;
constexpr double v = AT_COMPILATION(f, 0L);
std::cout << AT_COMPILATION(g, 5, 2) << std::endl;
}