-1

Suppose I have a template class like

template<class T> class Foo{
    T a;
    auto baz(){
        return 4.2f;
    }
};

int main(){
    Foo<int> bar;
    return 0;
}

Is there a tool which can convert this code to actual class and give output as :

class Foo{
    int a;
    float baz(){
        return 4.2f;
    }
};
// main goes below this line

A tool that replaces all auto and template arguments with deduced types.

I was working with templates and was curious if there was any such tool as it could be a good for learning type deduction?

coder3101
  • 3,920
  • 3
  • 24
  • 28

1 Answers1

5

I mean, the compiler does this. The type you expanded to Foo should really be called Foo<int>, and you'll see that if you step through your compiled program in a debugger.

I don't know of any tool that does a textual expansion though, and I'm pretty certain I wouldn't enjoy reading its output for any non-trivial program, especially one using standard library containers.


Edit - OK, this is still off-topic but, since I already answered, this seems relevant:

https://cppinsights.io

which expands your original code like so (link)

template<class T> class Foo{
    T a;
    auto baz(){
        return 4.2f;
    }
};

/* First instantiated from: insights.cpp:9 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class Foo<int>
{
  int a;
  inline auto baz();

  // inline Foo() noexcept = default;
  // inline constexpr Foo(const Foo<int> &) = default;
  // inline constexpr Foo(Foo<int> &&) = default;
};

#endif


int main()
{
  Foo<int> bar = Foo<int>();
  return 0;
}

You'll notice it never emits the Foo<int>::baz() you wanted though, just because it was never actually used.

Useless
  • 64,155
  • 6
  • 88
  • 132
  • Thanks. I was looking for a tool like this. I know I will not be using STL and it has less usability. It was just meant for learning how the compiler does type deductions. – coder3101 Mar 13 '19 at 20:09