C++: pointer to member as template argument and inline

Kristian Spangsege kristian.spangsege@gmail.com
Sun Aug 6 18:47:00 GMT 2006


It seems the answer to my question is "no" :-(

With GCC 4.0.2 (using -O3) the call to 'inc' does not get inlined in
following code:

struct S
{
  int inc(int v)
  {
    return v+1;
  }

  template<int (S::*f)(int)> int call(int v)
  {
    return (this->*f)(v);
  }

  int func(int v)
  {
    return call<&S::inc>(v);
  }
};

int main()
{
  S s;

  return s.func(6);
}



This is kind of surprising since in this next example the call to
'inc' does get inlined:

int inc(int v)
{
  return v+1;
}

template<int (*f)(int)> int call(int v)
{
  return (*f)(v);
}

int func(int v)
{
  return call<&inc>(v);
}

int main()
{
  return func(6);
}


Why does GCC optimizer discriminate between these two scenarios so
drasticly? I wonder if this is intensionally...


On 8/6/06, Kristian Spangsege <kristian.spangsege@gmail.com> wrote:
> Hi,
>
> Is GCC able to inline a method when that method is passed as a
> pointer-to-member template argument and then called with the syntax
> (this->*foo)(...) ?
>


-- 
"Will robots inherit the earth? Yes, but they will be our children. We
owe our minds to the deaths and lives of all the creatures that were
ever engaged in the struggle called Evolution. Our job is to see that
all this work shall not end up in meaningless waste."
                                              -- MARVIN L. MINSKY



More information about the Gcc-help mailing list