简体   繁体   English

从函数模板错误返回修改后的值

[英]return modified value from a function template error

My code is something like this: 我的代码是这样的:

   // ... code

   template <int i>
   int modifyparameter()
   {
     i = i++;
     return i;
   }

   // ... some more code

   int main()
   {
        int answer = modifyparameter<5>();
        cout << answer; //expecting 6
   }

But I am getting errors. 但我收到了错误。 What have I done wrong? 我做错了什么?

i is the name of an int value , and you cannot modify values. i是int 的名称,您无法修改值。 You probably want one of these: 你可能想要其中一个:

template <typename Number>
Number functional(Number x)
{
    return x + 1;
}

template <typename Number>
Number& side_effect(Number& x)
{
    return ++x;
}

i is not an lvalue , so i++ is illegal. i不是lvalue ,所以i++是非法的。

14.1/5 says. 14.1/5说。

A non-type non-reference template-parameter is not an lvalue. 非类型非参考模板参数不是左值。 It shall not be assigned to or in any other way have its value changed. 不得分配或以任何其他方式更改其值。

Post-increment operator ( ++ ) requires an lvalue as an operand. 后增量运算符( ++ )需要lvalue作为操作数。

Try: 尝试:

template <int i>
int modifyparameter()
{
  int copy_of_i = i;
  copy_of_i++;
  return copy_of_i;
}

There's nothing you can do to modify i itself, template parameters are compile-time constants. 没有什么可以修改i自己,模板参数是编译时常量。 However, you could make it act as if I was being modified by using a variable with static lifetime: 但是,您可以通过使用具有静态生存期的变量来使其行为,就像我被修改一样:

template <int i>
int modifyparameter()
{
  static int copy_of_i = i;
  copy_of_i++;
  return copy_of_i;
}

While it's not asked for, this seems to cry out for a compile-time solution: 虽然没有被要求,但这似乎是为编译时解决方案而哭泣:

template< int I >
struct increment { static const int result = I+1; };

std::cout << increment<41>::result << '\n';

That struct is what's called a meta-function. struct就是所谓的元函数。 Yes, it's a struct, but it's used (at compile-time) like a function: you call it, passing a parameter, and you get back a result. 是的,它是一个结构体,但是它(在编译时)就像一个函数一样使用:你调用它,传递一个参数,然后你得到一个结果。 The syntax is hilarious, but that's because nobody actually planned to do this; 语法很搞笑,但那是因为没有人真正计划这样做; the possibility was discovered (more or less) by accident. 这种可能性是偶然发现的(或多或少)。

Doing this at compile-time has the advantage that the result is a compile-time constant and can be used as such: 在编译时执行此操作的优点是结果是编译时常量,可以这样使用:

int my_array[increment<7>::result]; // array of 7+1 ints

Of course, defining an array like this is nonsense. 当然,定义这样的数组是无稽之谈。 Just as in run-time algorithms, incrementing is usually just one operation of an algorithm that computes something more complex. 就像在运行时算法中一样,递增通常只是计算更复杂事物的算法的一个操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM