Search code examples
c++templatesc++11instantiationdecltype

Can I instantiate a template without repeating its signature?


I want to instantiate some function with a long signature:

template<typename T> void foo(
    T& t,
    SomeType some_parameter,
    AnotherType another_parameter,
    EtcType yet_another_parameter,
    AsYouCanTell this_is_a_very_long_signature);

The straightforward way to instantiate foo is:

template void foo<int>(
    int& t,
    SomeType some_parameter,
    AnotherType another_parameter,
    EtcType yet_another_parameter,
    AsYouCanTell this_is_a_very_long_signature);

but that's a duplication of the long signature. And what if I want specific instantiation for 5 different types - do I copy it 5 times? Doesn't make sense...

I was thinking maybe I could write

template decltype(foo<int>);

but for some reason this doesn't work. Can I make it work, somehow?


Solution

  • You can, indeed, instantiate your function without repeating its signature - but the syntax is a little different:

    template
    decltype(foo<int>) foo<int>;
    

    decltype gives you a type but the explicit instantiation requires a declaration which is a type followed by a name.

    Tried with GCC 4.9.1; it works as expected and compiles without any warnings even with the -pedantic flag.