简体   繁体   中英

Compile-time recursion in variadic templates

my goal is to make a class containing a tuple consisting of classes all of which have a method void update() which allows all the contained update() methods to be called in a row with minimal overhead. Here is my code:

template< typename... Tel >
class ExecSet
{
private:
  std::tuple<Tel...> m_data;

   //Compile-time Recursive
   template<int _iter, typename _Head, typename... _Tail>
   inline void _update()
   {
     std::get<_iter>(m_data).update();
     _update< _iter + 1, _Tail... >();
   }

   //Base case
   template<int _iter>
   inline void _update()
   {
     //Do nothing here
   }

public:
   inline void update()
   {
     _update<0, Tel...>();
   }
};

class Foo
{
//..
inline void update()
  {
    std::cout << "An update of Foo " << m_i << "\n";
  }

  private:
  int m_i;
};

class Bar
{
//..
inline void update()
  {
    std::cout << "An update of Bar " << m_i << "\n";
  }

  private:
  int m_i;
};

The code compiles and a test executes as expected. My question is, can I be 100% sure that ExecSet::update() will be completely inlined along with every recursed call made inside? I would imagine it should because this is all determined at compile time. And under -O3 everything should be inlined too right?

No, you cannot. C++ standard does not guarantee function to be inlined even if you add inline specifier.

You can ask the compiler to emit symbolic assembly instead of machine code and check for yourself. That said, having done just that on multiple occasions myself, I'm sure no serious compiler would leave such a mundane opportunity to inline unused. The things modern compilers do, they are pure magic .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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