Template function as a template argument - c++

I've just got confused how to implement something in a generic way in C++. It's a bit convoluted, so let me explain step by step.
Consider such code:
void a(int) {
// do something
}
void b(int) {
// something else
}
void function1() {
a(123);
a(456);
}
void function2() {
b(123);
b(456);
}
void test() {
function1();
function2();
}
It's easily noticable that function1 and function2 do the same, with the only different part being the internal function.
Therefore, I want to make function generic to avoid code redundancy. I can do it using function pointers or templates. Let me choose the latter for now. My thinking is that it's better since the compiler will surely be able to inline the functions - am I correct? Can compilers still inline the calls if they are made via function pointers? This is a side-question.
OK, back to the original point... A solution with templates:
void a(int) {
// do something
}
void b(int) {
// something else
}
template<void (*param)(int) >
void function() {
param(123);
param(456);
}
void test() {
function<a>();
function<b>();
}
All OK. But I'm running into a problem: Can I still do that if a and b are generics themselves?
template<typename T>
void a(T t) {
// do something
}
template<typename T>
void b(T t) {
// something else
}
template< ...param... > // ???
void function() {
param<SomeType>(someobj);
param<AnotherType>(someotherobj);
}
void test() {
function<a>();
function<b>();
}
I know that a template parameter can be one of:
a type,
a template type,
a value of a type.
None of those seems to cover my situation. My main question is hence: How do I solve that, i.e. define function() in the last example?
(Yes, function pointers seem to be a workaround in this exact case - provided they can also be inlined - but I'm looking for a general solution for this class of problems).

In order to solve this problem with templates, you have to use a template template parameter.
Unfortunately, you cannot pass template template function as a type, because it has to be instantiated first. But there is a workaround with dummy structures. Here is an example:
template <typename T>
struct a {
static void foo (T = T ())
{
}
};
template <typename T>
struct b {
static void foo (T = T ())
{
}
};
struct SomeObj {};
struct SomeOtherObj {};
template <template <typename P> class T>
void function ()
{
T<SomeObj>::foo ();
T<SomeOtherObj>::foo ();
}
int main ()
{
function<a>();
function<b>();
}

With generic lambda from C++14 you might do:
template<typename T> void a(T t) { /* do something */}
template<typename T> void b(T t) { /* something else */ }
template <typename F>
void function(F&& f) {
f(someobj);
f(someotherobj);
}
void test() {
// For simple cases, auto&& is even probably auto or const auto&
function([](auto&& t){ a(t); });
function([](auto&& t){ b(t); });
// For perfect forwarding
function([](auto&& t){ a(std::forward<decltype(t)>(t)); });
function([](auto&& t){ b(std::forward<decltype(t)>(t)); });
}
Can compilers still inline the calls if they are made via function pointers?
They can, but it is indeed more complicated, and they may fail more often than with functor or template.

Here's a way. It may not be the best, but it works:
template <typename T, T param>
void function() {
param(123);
param(456);
}
void test()
{
function< void(*)(int), a<int> >(); // space at end necessary to compiler
function< void(*)(int), b<int> >(); // because the C++ grammar is ambiguous
}
Whether or not they'll be inlined depends on the compiler, but I would be rather surprised if they weren't.
EDIT: Okay, I'm a little off today and missed the part where the parameters are of different types. My bad.
There may be a tricky way to do this with templates, but this is the easiest way I could think of:
#define function(x) do { x<thing1>(obj1); x<thing2>(obj2) } while(0)
I know, I know, "macros are evil," blah blah blah. It works. If function needs to be more complicated than your example you may run into problems, but it is much easier than anything I've been able to come up with.

template < typename F >
void function(F f)
{
f(123);
}
void a(int x) { ... }
struct b { void operator() (int x) { ... } };
void outer()
{
function(&a);
function(b());
}

Related

Return function pointer by auto filling template parameters [duplicate]

I've just got confused how to implement something in a generic way in C++. It's a bit convoluted, so let me explain step by step.
Consider such code:
void a(int) {
// do something
}
void b(int) {
// something else
}
void function1() {
a(123);
a(456);
}
void function2() {
b(123);
b(456);
}
void test() {
function1();
function2();
}
It's easily noticable that function1 and function2 do the same, with the only different part being the internal function.
Therefore, I want to make function generic to avoid code redundancy. I can do it using function pointers or templates. Let me choose the latter for now. My thinking is that it's better since the compiler will surely be able to inline the functions - am I correct? Can compilers still inline the calls if they are made via function pointers? This is a side-question.
OK, back to the original point... A solution with templates:
void a(int) {
// do something
}
void b(int) {
// something else
}
template<void (*param)(int) >
void function() {
param(123);
param(456);
}
void test() {
function<a>();
function<b>();
}
All OK. But I'm running into a problem: Can I still do that if a and b are generics themselves?
template<typename T>
void a(T t) {
// do something
}
template<typename T>
void b(T t) {
// something else
}
template< ...param... > // ???
void function() {
param<SomeType>(someobj);
param<AnotherType>(someotherobj);
}
void test() {
function<a>();
function<b>();
}
I know that a template parameter can be one of:
a type,
a template type,
a value of a type.
None of those seems to cover my situation. My main question is hence: How do I solve that, i.e. define function() in the last example?
(Yes, function pointers seem to be a workaround in this exact case - provided they can also be inlined - but I'm looking for a general solution for this class of problems).
In order to solve this problem with templates, you have to use a template template parameter.
Unfortunately, you cannot pass template template function as a type, because it has to be instantiated first. But there is a workaround with dummy structures. Here is an example:
template <typename T>
struct a {
static void foo (T = T ())
{
}
};
template <typename T>
struct b {
static void foo (T = T ())
{
}
};
struct SomeObj {};
struct SomeOtherObj {};
template <template <typename P> class T>
void function ()
{
T<SomeObj>::foo ();
T<SomeOtherObj>::foo ();
}
int main ()
{
function<a>();
function<b>();
}
With generic lambda from C++14 you might do:
template<typename T> void a(T t) { /* do something */}
template<typename T> void b(T t) { /* something else */ }
template <typename F>
void function(F&& f) {
f(someobj);
f(someotherobj);
}
void test() {
// For simple cases, auto&& is even probably auto or const auto&
function([](auto&& t){ a(t); });
function([](auto&& t){ b(t); });
// For perfect forwarding
function([](auto&& t){ a(std::forward<decltype(t)>(t)); });
function([](auto&& t){ b(std::forward<decltype(t)>(t)); });
}
Can compilers still inline the calls if they are made via function pointers?
They can, but it is indeed more complicated, and they may fail more often than with functor or template.
Here's a way. It may not be the best, but it works:
template <typename T, T param>
void function() {
param(123);
param(456);
}
void test()
{
function< void(*)(int), a<int> >(); // space at end necessary to compiler
function< void(*)(int), b<int> >(); // because the C++ grammar is ambiguous
}
Whether or not they'll be inlined depends on the compiler, but I would be rather surprised if they weren't.
EDIT: Okay, I'm a little off today and missed the part where the parameters are of different types. My bad.
There may be a tricky way to do this with templates, but this is the easiest way I could think of:
#define function(x) do { x<thing1>(obj1); x<thing2>(obj2) } while(0)
I know, I know, "macros are evil," blah blah blah. It works. If function needs to be more complicated than your example you may run into problems, but it is much easier than anything I've been able to come up with.
template < typename F >
void function(F f)
{
f(123);
}
void a(int x) { ... }
struct b { void operator() (int x) { ... } };
void outer()
{
function(&a);
function(b());
}

Passing different datatypes via a loop

Lets say I have a function
template<typename T>
some_function(T a){
// some operations..
}
I have a huge list of classes who objects i want to pass to the function one by one(Don't ask me why I'm forced to have it like that.)
class type1{ //.. whateever is necessary here...
};
class type2{ //.. whateever is necessary here...
};
class type3{ //.. whateever is necessary here...
};
class type4{ //.. whateever is necessary here...
};
.
.
and so on
Is there a way I can instantiate an object of each data and pass it to the function within a loop, rather than type one by one it manually.
(It would be better if the instantiation happens within the loop so that the object is local for every loop).
Any way to approach this problem other than typing it manually is welcome.
EDIT:
Since there were questions in the comments. Let me elaborate on the type of algorithm I am looking for.
Step 1: Pick a class my_class in [type1,type2,...,typeN]
Step 2: Instantiate an object of that class my_class object
Step 3: Pass it to the function some_function(object)
Step 4: Go to step 1 and pick the next class.
I hope I made things clear.
EDIT 2: I use c++11 . But I don't mind switching if it is needed
Let me elaborate on the type of algorithm I am looking for.
Step 1: Pick a class my_class in [type1,type2,...,typeN]
Step 2: Instantiate an object of that class my_class object
Step 3: Pass it to the function some_function(object)
Step 4: Go to step 1 and pick the next class.
If you can use C++11 or newer, and if you can pass immediately the object instantiated to some_function(), you can simulate a loop with a variadic template type list as follows
template <typename ... Ts>
void repeatOverTypes ()
{
using unused=int[];
(void)unused { 0, (some_function(Ts{}), 0)... };
}
The following is a full compiling example
#include <iostream>
class type_1 { };
class type_2 { };
class type_3 { };
class type_4 { };
template <typename T>
void some_function (T a)
{ }
template <typename ... Ts>
void repeatOverTypes ()
{
using unused=int[];
(void)unused { 0, (some_function(Ts{}), 0)... };
}
int main ()
{
repeatOverTypes<type_1, type_2, type_3, type_4>();
}
If you can use C++17, using folding repeatOverTypes() become simply
template <typename ... Ts>
void repeatOverTypes ()
{ (some_function(Ts{}), ...); }
-- EDIT --
The OP say
I overlooked an important detail while trying to simplify the problem. I need to pass the objects by reference. So the Ts{} won't work ? What can i do ?
I see... well, I suppose you can (1) create the Ts{} object and store they in a container (a std::tuple seems to me an obvious container) and (2) pass to some_function() the values extracted from the tuple.
The point (1) is simple
std::tuple<Ts...> t { Ts{}... };
The point (2) heavily depend from the list of type (there are repetitions in "type1,type2,...,typeN" ?) and the exact language.
If all types in the list are different and you can use C++14, you can access the tuple values trough std::get<Ts>(t); so the function can be written
template <typename ... Ts>
void repeatOverTypes ()
{
using unused=int[];
std::tuple<Ts...> t { Ts{}... };
(void)unused { 0, (some_function(std::get<Ts>(t)), 0)... };
}
If there are repetitions, you have to access value via integer index, so you have to create a list of index and pass they to an helper function; something like
template <typename T, std::size_t ... Is>
void rotH (T & t, std::index_sequence<Is...> const &)
{
using unused=int[];
(void)unused { 0, (some_function(std::get<Is>(t)), 0)... };
}
template <typename ... Ts>
void repeatOverTypes ()
{
std::tuple<Ts...> t { Ts{}... };
rotH(t, std::make_index_sequence<sizeof...(Ts)>{});
}
Unfortunately std::index_sequence and std::make_index_sequence are introduced in C++14 so, in C++11, you have to simulate they in some way.
As usual in C++17 is simpler; if you are sure (but really, really sure) that types are all different, the function is simply
template <typename ... Ts>
void repeatOverTypes ()
{
std::tuple<Ts...> t { Ts{}... };
(some_function(std::get<Ts>(t)), ...);
}
In case of types collision, with integer sequence,
template <typename T, std::size_t ... Is>
void rotH (T & t, std::index_sequence<Is...> const &)
{ (some_function(std::get<Is>(t)), ...); }
template <typename ... Ts>
void repeatOverTypes ()
{
std::tuple<Ts...> t { Ts{}... };
rotH(t, std::make_index_sequence<sizeof...(Ts)>{});
}
I have a huge list of classes who objects i want to pass to the function one by one
As you seem to need handling many types and avoid to type them out hardcoded in a single place of your code (as provided in this answer), you should consider using dynamic polymorphism, interfaces and self-registering classes rather.
This is a well known technique when a uniform set of operations needs to be done over a lot of specific class types. Many unit testing frameworks use that in order to avoid that additional test cases need to be added at a central place, but just within the translation unit where they're defined.
Here's a sketch (untested) how to implement such:
Provide an interface to describe what needs to be done in some_function() uniquely:
struct IMyInterface {
virtual ~IMyInterface() {}
virtual void WhatNeedsToBeDone() = 0;
virtual int WhatNeedsToBeKnown() const = 0;
};
void some_function(IMyInterface* intf) {
if(intf->WhatNeedsToBeKnown() == 1) {
intf->WhatNeedsToBeDone();
}
}
Provide a singleton registrar keeping a map of functions to create your classes:
class MyRegistrar {
MyRegistrar() {};
using FactoryFunction = std::function<std::unique_ptr<IMyInterface> ()>;
std::map<std::string, FactoryFunction> classFactories;
public:
static MyRegistrar& ClassRegistry() {
static MyRegistrar theRegistrar;
return theRegistrar;
};
template<typename T>
void registerClassFactory(
FactoryFunction factory) {
classFactories[typeid(T).name()] = factory;
};
template<typename T>
std::unique_ptr<IMyInterface> createInstance() {
return classFactories[typeid(T).name()]();
}
template<typename T>
const FactoryFunction& factory() const {
return classFactories[typeid(T).name()];
}
std::vector<FactoryFunction> factories() const {
std::vector<FactoryFunction> result;
for(auto& factory : classFactories) {
result.push_back(factory);
}
return result;
}
};
also provide a registration helper to make it easier registering the types with the global registrar
template<typename T>
struct RegistrationHelper {
RegistrationHelper(
std::function<std::unique_ptr<IMyInterface> ()> factoryFunc =
[](){ return std::make_unique<T>(); }) {
MyRegistrar::ClassRegistry().registerClassFactory<T>(factoryFunc);
}
};
In your specific types you can use that like
class type1 : public IMyInterface {
static RegistrationHelper<type1> reghelper;
public:
void WhatNeedsToBeDone() override {}
int WhatNeedsToBeKnown() const override { return 0; };
};
RegistrationHelper<type1> type1::reghelper;
You can also specialize to deviate from the default factory function:
enum Color { Red, Green };
class type1 : public IMyInterface {
static RegistrationHelper<type1> reghelper;
Color color_;
public:
type1(Color color) : color_(color) {}
void WhatNeedsToBeDone() override {}
int WhatNeedsToBeKnown() const override { return 0; };
};
RegistrationHelper<type1> type1::reghelper(
[](){ return std::make_unique<type1>(condition? Green : Red);
} -> std::function<std::unique_ptr<IMyInterface> ()>
);
To realize your iteration over all classes you can use
for(auto factory : MyRegistrar::ClassRegistry().factories()) {
std::unique_ptr<IMyInterface> intf = factory();
some_function(intf.get());
}

Is this "Tag Dispatching"?

Say I have some code:
void barA() { }
void barB() { }
void fooA() {
// Duplicate code...
barA();
// More duplicate code...
}
void fooB() {
// Duplicate code...
barB();
// More duplicate code...
}
int main() {
fooA();
fooB();
}
And I want to remove the duplicate code between fooA and fooB I could use a number of dynamic techniques such as passing in a bool parameter, passing a function pointer or virtual methods but if I wanted a compile time technique I could do something like this:
struct A { };
struct B { };
template<typename Tag> void bar();
template<> void bar<A>() { }
template<> void bar<B>() { }
template<typename Tag> void foo() {
// Duplicate code
bar<Tag>();
// More duplicate code
}
int main() {
foo<A>();
foo<B>();
}
where I have introduced two empty "Tag" classes to indicate which bar to use and templated foo and bar based on the tag class. This seems to do the trick. Questions:
Does this technique have a name? is this an example of "Tag dispatching"? From what I read about Tag dispatching it is slightly different and involves function overloading with a tag parameter. A tag that may have come from a typedef in a trait class.
Is there a more idomatic compile-time technique of achieving the same thing?
Edit:
Another possibility would be to use function overloading of bar instead of template specialization and pass the tag class as a parameter:
struct A { };
struct B { };
void bar(A) { }
void bar(B) { }
template<typename Tag> void foo() {
// Duplicate code
bar(Tag());
// More duplicate code
}
int main() {
foo<A>();
foo<B>();
}
This isn't tag dispatching. As you rightly said in your question, that'd be if you used some compile time trait of A and B to distinguish between the two, and then use that to select between two different overloads.
An good example of tag dispatch would be how std::advance is typically implemented. The function's signature is
template< class InputIt, class Distance >
void advance( InputIt& it, Distance n );
it can be advanced n positions in a single operation if it meets the requirements of RandomAccessIterator. For lesser iterators we must advance it in a loop. So an implementation would probably do something similar to the following:
namespace detail
{
template<class InputIt, class Distance>
void advance(InputIt& it, Distance n, std::random_access_iterator_tag)
{
it += n;
}
template<class InputIt, class Distance>
void advance(InputIt& it, Distance n, std::bidirectional_iterator_tag)
{
if(n < 0) {
while(n++) --it;
} else {
while(n--) ++it;
}
}
template<class InputIt, class Distance>
void advance(InputIt& it, Distance n, std::input_iterator_tag)
{
assert(n >= 0);
while(n--) ++it;
}
}
template< class InputIt, class Distance >
void advance( InputIt& it, Distance n )
{
detail::advance(it, n,
typename std::iterator_traits<InputIt>::iterator_category());
}
I don't know of any specific name for what you're doing. It's just an example of how one would follow the DRY principle.
If bar took an instance of A and B as an argument, then I'd implement this differently. Instead of making bar a function template, and then providing specializations, I'd let overload resolution do the job for me.
void bar(A const&) { ... }
void bar(B const&) { ... }
But since that's not the case, providing explicit specializations seems the right way to do this.

template magic for wrapping C callbacks that take void* parameters?

Say I'm using a C API that lets you register callbacks that take a void* closure:
void register_callback(void (*func)(void*), void *closure);
In C++ it's nice to have stronger types than void* so I want to create a wrapper that lets me register strongly-typed C++ callbacks instead:
template <typename T, void F(T*)>
void CallbackWrapper(void *p) {
return F(static_cast<T*>(p));
}
void MyCallback(int* param) {}
void f(void *closure) {
register_callback(CallbackWrapper<int, MyCallback>, closure);
}
This works alright. One nice property of this solution is that it can inline my callback into the wrapper, so this wrapping scheme has zero overhead. I consider this a requirement.
But it would be nice if I could make the API look more like this:
void f2() {
RegisterCallback(MyCallback, closure);
}
I hope I can achieve the above by inferring template parameters. But I can't quite figure out how to make it work. My attempt so far is:
template <typename T>
void RegisterCallback(void (*f)(T*), T* closure) {
register_callback(CallbackWrapper<T, f>, closure);
}
But this doesn't work. Anyone have a magic incantation that will make f2() work above, while retaining the zero-overhead performance characteristic? I want something that will work in C++98.
This template function improves the syntax marginally.
template <typename T, void F(T*)>
void RegisterCallback (T *x) {
register_callback(CallbackWrapper<T, F>, x);
}
int x = 4;
RegisterCallback<int, MyCallback>(&x);
If you are willing to use a functor rather than a function to define your callback, then you can simplify things a bit more:
#ifdef HAS_EXCEPTIONS
# define BEGIN_TRY try {
# define END_TRY } catch (...) {}
#else
# define BEGIN_TRY
# define END_TRY
#endif
template <typename CB>
void CallbackWrapper(void *p) {
BEGIN_TRY
return (*static_cast<CB*>(p))();
END_TRY
}
struct MyCallback {
MyCallback () {}
void operator () () {}
};
template <typename CB>
void RegisterCallback (CB &x) {
register_callback(CallbackWrapper<CB>, &x);
}
MyCallback cb;
RegisterCallback(cb);
But, as others have mentioned, you run the risk of the code not porting correctly to a system where the C ABI and C++ ABI differ.
I have discovered a better answer to this question than the other answers given to me here! (Actually it was another engineer inside Google who suggested it).
You have to repeat the function name twice, but that can be solved with a macro.
The basic pattern is:
// Func1, Func2, Func3: Template classes representing a function and its
// signature.
//
// Since the function is a template parameter, calling the function can be
// inlined at compile-time and does not require a function pointer at runtime.
// These functions are not bound to a handler data so have no data or cleanup
// handler.
template <class R, class P1, R F(P1)>
struct Func1 {
typedef R Return;
static R Call(P1 p1) { return F(p1); }
};
// ...
// FuncSig1, FuncSig2, FuncSig3: template classes reflecting a function
// *signature*, but without a specific function attached.
//
// These classes contain member functions that can be invoked with a
// specific function to return a Func/BoundFunc class.
template <class R, class P1>
struct FuncSig1 {
template <R F(P1)>
Func1<R, P1, F> GetFunc() { return Func1<R, P1, F>(); }
};
// ...
// Overloaded template function that can construct the appropriate FuncSig*
// class given a function pointer by deducing the template parameters.
template <class R, class P1>
inline FuncSig1<R, P1> MatchFunc(R (*f)(P1)) {
(void)f; // Only used for template parameter deduction.
return FuncSig1<R, P1>();
}
// ...
// Function that casts the first parameter to the given type.
template <class R, class P1, R F(P1)>
R CastArgument(void *c) {
return F(static_cast<P1>(c));
}
template <class F>
struct WrappedFunc;
template <class R, class P1, R F(P1)>
struct WrappedFunc<Func1<R, P1, F> > {
typedef Func1<R, void*, CastArgument<R, P1, F> > Func;
};
template <class T>
generic_func_t *GetWrappedFuncPtr(T func) {
typedef typename WrappedFunc<T>::Func Func;
return Func().Call;
}
// User code:
#include <iostream>
typedef void (generic_func_t)(void*);
void StronglyTypedFunc(int *x) {
std::cout << "value: " << *x << "\n";
}
int main() {
generic_func_t *f = GetWrappedFuncPtr(
MatchFunc(StronglyTypedFunc).GetFunc<StronglyTypedFunc>());
int x = 5;
f(&x);
}
This is not short or simple, but it is correct, principled, and standard-compliant!
It gets me what I want:
The user gets to write StronglyTypedFunc() taking a pointer to a specific thing.
This function can be called with a void* argument.
There is no virtual function overhead or indirection.
Why not make your closure a real closure (by including real typed state).
class CB
{
public:
virtual ~CB() {}
virtual void action() = 0;
};
extern "C" void CInterface(void* data)
{
try
{
reinterpret_cast<CB*>(data)->action();
}
catch(...){}
// No gurantees about throwing exceptions across a C ABI.
// So you need to catch all exceptions and drop them
// Or probably log them
}
void RegisterAction(CB& action)
{
register_callback(CInterface, &action);
}
By using an object you can introduce real state.
You have a clean C++ interface with correctly types objects.
Its easy to use you just derive from CB and implement action().
This also has the same number of actual function calls as you use. Because in your example you pass a function pointer to the wrapper (which can't be inlined (it can but it will take more static analysis then current compilers do)).
Apparently it does inline.

Deducing type, when using member function pointer as template argument

When I want to have member function as template argument, is there a way to templetize it without providing Caller type?
struct Foo
{
template <typename Caller, void (Caller::*Func)(int)>
void call(Caller * c) { (c->*Func)(6); }
};
struct Bar
{
void start()
{
Foo f;
f.call<Bar, &Bar::printNumber>(this);
^^^^
}
void printNumber(int i) { std::cout << i; }
};
int main ()
{
Bar b;
b.start();
return 0;
}
when I try
template <void (Caller::*Func)(int), typename Caller>
void call(Caller * c) { (c->*Func)(6); }
and call it like
f.call<&Bar::printNumber>(this);
I am getting Caller is not class... error.
So, is there a way to let compiler deduce the Caller type?
No, not as you want it. Caller could be deduced if
the pointer to member function were an parameter, not a template parameter. Eg:
template <class Caller>
void call(Caller * c, void (Caller::*Func)(int)) { (c->*Func)(6); }
it was known beforehand. For example, you could make the call look like this:
f.arg(this).call<&Bar::printNumber>();
The call function would look similar to this:
template <class Arg>
struct Binder
{
template<void (Arg::*Func)(int)>
void operator()() const {
...
}
};
The arg function would be easy to write (in your case it would return Binder<Bar>, where Bar is deduced from this).
Not very convenient, IMHO.