是否有机会制作元编程功能,但不能扩展编译中的所有参数?只想将一些参数作为运行时参数和一些编译。因为我知道其中一些将在1..10的范围内,但另一个是未知的(将在运行时知道)。
让我们使用标准元编程示例:
unsigned int factorial(unsigned int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
template <int n>
struct factorial {
enum { value = n * factorial<n - 1>::value };
};
template <>
struct factorial<0> {
enum { value = 1 };
};
// Usage examples:
// factorial<0>::value would yield 1;
// factorial<4>::value would yield 24.
以下是我的情况:
unsigned int cutom_imagined_function(unsigned int n, unsigned int runtime_param /* this will be given at runtime */) {
return n == 0 ? 1 : (n + runtime_param) * cutom_imagined_function(n - 1);
}
如何将上面的内容转换为元编程?运行这个让我们说如下(或类似的):
// int variable;
// variable = get_var_from_user();
// cutom_imagined_function<4>::value(variable)
答案 0 :(得分:4)
您可以使用相同的方法:常量表达式成为模板参数,其他一切都不会:
template <unsigned int N>
struct cutom_imagined
{
static unsigned int function(unsigned int r)
{
return (N + r) * cutom_imagined<N - 1>::function(r);
}
};
template <>
struct cutom_imagined<0>
{
static unsigned int function(unsigned int) { return 1; }
};
用法:
unsigned int result = cutom_imagined<N>::function(get_input());
答案 1 :(得分:3)
假设你的意思是:
unsigned int cutom_imagined_function(
unsigned int n,
unsigned int runtime_param)
{
return n == 0 ? 1 : (n+runtime_param)*custom_imagined_function(n-1, runtime_param);
}
这是我认为你描述的一般概念。它实际上非常简单。使功能本身成为模板。
template<unsigned int in>
unsigned int custom_imagined_function(unsigned int runtime_param) {
return (n+runtime_param)*custom_imagined_function<n-1>(runtime_param);
}
template<>
unsigned int custom_imagined_function<0>(unsigned int runtime_param) {
return 1;
}
int main() {
int variable;
std::cin >> variable;
unsigned int result = custom_imagined_function<4>(variable);
}
或者,您可以使用稍微冗长的std::integral_constant
。
unsigned int custom_imagined_function(
std::integral_constant<unsigned int,0>,
unsigned int runtime_param)
{
return 1;
}
template<unsigned int in>
unsigned int custom_imagined_function(
std::integral_constant<unsigned int,n>,
unsigned int runtime_param)
{
std::integral_constant<unsigned int,n-1> less;
return (n+runtime_param) * custom_imagined_function(less, runtime_param);
}
int main() {
std::integral_constant<unsigned int,4> four;
int variable;
std::cin >> variable;
unsigned int result = custom_imagined_function(four, variable);
}
此外,既然我们已经constexpr
(在某些编译器中),factorial
很容易简化:
constexpr unsigned int factorial(unsigned int n) {
return n==0?1:n*factorial(n-1);
}