2
votes

I need to instantiate a templated function foo() with a long signature, for some specific template arguments.

I just read the answers to this question which essentially suggest copying the function signature but setting the specific arguments. I want to avoid that somehow. What is a reasonable way to achieve this? e.g. something which would allow me to write

INSTANTIATE(foo, template_arg1, template_arg2);

or maybe

MyFunctionType<template_arg1, template_arg2> foo;

Just for illustrative purposes, suppose this is the code for foo:

template<typename T, int val>
unsigned foo(
    T bar,
    SomeType baz1,
    SomeOtherType baz2,
    YetAnotherType you_catch_the_drift) 
{ 
    /* some code here */ 
}
2
@jrok: I don't think it matters, but see my edit now.einpoklum
In C++11 you could use template aliases to make an alias to your function type partially parametrized. This helps if your function has too many parameters, but some of them are well known (Used frequently) but some others are not and should be specified by the user of the function type.Manu343726
The same applies for the function usage, not only the instantation/declaration of its type. You could use std::bind() to bind well known parameters and reduce the number of parameters the user should specify at the call point.Manu343726
@Manu343726: Can you give example code? Also, I could make the return type very long and tedious, e.g. std::tuple<std::map<SomeLongType,AnotherLongType>, std::vector<std::list<AThirdLongType>>` or something.einpoklum

2 Answers

0
votes

In explicit instantiations of function templates it's possible to omit the template parameter list after template-id if all arguments can be deduced:

template<typename T> void foo(T) {}
template void foo(int); // explicit instantiation
//               ^ no template parameter list here

Not in your case, though, since val parameter needs to be passed explicitly. This is how your explicit instantiation could look like:

template unsigned foo<int, 0>(int, char, double, float);

Is it that bad? You can write a macro to avoid some duplication, but looks like there isn't much of it in the first place.

0
votes

You can simply define a macro:

#define INSTANTIATE_FOO(T, val) \
template \
unsigned foo<T, val>( \
    T bar, \
    SomeType baz1, \
    SomeOtherType baz2, \
    YetAnotherType you_catch_the_drift);

And use it in the following way:

INSTANTIATE_FOO(int, 0)