constexpr函数参数作为模板参数 [英] constexpr function parameters as template arguments

查看:163
本文介绍了constexpr函数参数作为模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩一些玩具代码,使用c ++ 11来更多地了解事情的工作原理。在这期间,我遇到了以下问题,简化到:

I am playing around with some toy code using c++11 to figure out a bit more about how things work. During this I came across the following issue that simplifies down to:

template <int x, int y>
class add {
public:
    static constexpr int ret = x + y;
};

constexpr int addFunc(const int x, const int y) {
    return add<x,y>::ret;
}

int main() {
    const int x = 1;
    const int y = 2;
    cout << add<x,y>::ret << endl; // Works
    cout << addFunc(1,2) << endl;  // Compiler error
    return 0;
}



我使用GCC 4.8.1,输出是: >
'x'不是类型为'int'的模板参数中的常量表达式

'y'不是类型为'int'的模板参数中的常量表达式

I'm using GCC 4.8.1 and the output is:
'x' is not a constant expression in template argument for type 'int'
'y' is not a constant expression in template argument for type 'int'

我试图计算 add :: ret 的两种方式之间的区别是什么?这两个值都应该在编译时可用。

What exactly is the difference between the two ways I am trying to calculate add::ret? Both of these values should be available at compile time.

推荐答案

你告诉编译器, addFunc 将是一个constexpr。但它依赖于参数,这不是constexpr本身,所以编译器已经扼杀了。标记它们const仅意味着你不会在函数体中修改它们,并且此时不考虑对函数进行的特定调用。

You tell the compiler, that addFunc would be a constexpr. But it depents on parameters, that are not constexpr itself, so the compiler already chokes on that. Marking them const only means you are not going to modify them in the function body, and the specific calls you make to the function are not considered at this point.

一个方法,你可以让编译器理解你只会传递编译时常数到 addFunc :使参数一个模板参数本身:

There is a way you can make the compiler understand you are only going to pass compile time constants to addFunc: Make the parameters a template parameters itself:

template <int x, int y>
constexpr int addFunc() {
    return add<x,y>::ret;
}

然后调用

cout << addFunc<1,2>() << endl;

这篇关于constexpr函数参数作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆