Syntax help. Template operator() in template function object - c++

What is the proper syntax I need to run what I'm trying to run in main() below?
#include <iostream>
#include <vector>
template <int... Is>
void foo() {
std::vector<int> v{Is...};
for (int x : v) std::cout << x << ' ';
}
template <int... Is>
struct Foo {
template <typename T, typename... Ts>
void operator()() const {
std::cout << sizeof(T) << ' ' << sizeof...(Ts) << '\n';
foo<Is...>();
}
};
int main() {
// Foo<0,1,2>()<bool, char, long>();
Foo<0,1,2> f;
f<bool, char, long>(); // Won't compile
}

I don't think you can manually specify template arguments for operator overloads. However, you can write
f.operator()<bool, char, long>();

Related

single-line std::get std::index_sequence?

I have a std::tuple, and I want to unwrap the contents using std::index_sequence in order to call a variadic function template
Consider the following example code:
#include <iostream>
#include <tuple>
template<typename... Ts>
void foo(const std::string& s, Ts... ts)
{
std::cout << "foo called with " << s << " and " << sizeof...(Ts) << " ts\n";
}
template<typename Tuple, std::size_t... Ixs>
void call_foo(const std::string& s, Tuple& t, std::index_sequence<Ixs...>)
{
foo(s, std::get<Ixs>(t)...);
}
template<typename... Ts>
struct Bar
{
Bar(Ts... ts) : t(ts...)
{ }
void do_it()
{
call_foo("hi", t, std::make_index_sequence<std::tuple_size<decltype(t)>::value>{});
}
std::tuple<Ts...> t;
};
template<typename... Ts> Bar<Ts...> make_bar(Ts... ts) { return Bar<Ts...>(ts...); }
int main ()
{
auto bar = make_bar(1, 'a', 2.3);
bar.do_it();
}
Note that I have to call through call_foo with my index_sequence in order to "unwrap" the index_sequence for calling std::get...
Is it possible to forego the intermediate call_foo function, and call foo directly?
That is, unwrap the tuple directly at the call-site?
If you don't want to or can't use std::apply, I can suggest a few alternatives.
The snippets below are based on the previous revision of your question that didn't have the class Bar in it. The same solutions work for the new revision as well.
(1) You could replace call_foo with a C++20 lambda with an explicit template parameter list:
#include <cstddef>
#include <iostream>
#include <tuple>
#include <utility>
template<typename... Ts>
void foo(const std::string& s, Ts... ts)
{
std::cout << "foo called with " << s << " and " << sizeof...(Ts) << " ts\n";
}
template<typename... Ts>
void bar(Ts... ts)
{
const std::string s = "hello world";
const auto t = std::make_tuple(ts...);
[&]<std::size_t ...I>(std::index_sequence<I...>)
{
foo(s, std::get<I>(t)...);
}
(std::make_index_sequence<std::tuple_size_v<decltype(t)>>{});
}
int main()
{
bar(1, 'a', 2.3);
}
Try it live
Unfortunately, GCC 8 currently seems to be the only major compiler that supports those.
(2) If your compiler doesn't have the new fancy lambdas, or you don't want to write the index_sequence boilerplate every time you need to expand the tuple, I suggest following:
#include <cstddef>
#include <iostream>
#include <tuple>
#include <utility>
template <std::size_t ...I, typename F> void with_sequence_impl(F &&func, std::index_sequence<I...>)
{
func(std::integral_constant<std::size_t, I>{}...);
}
template <std::size_t N, typename F> void with_sequence(F &&func)
{
with_sequence_impl(std::forward<F>(func), std::make_index_sequence<N>{});
}
template<typename... Ts>
void foo(const std::string& s, Ts... ts)
{
std::cout << "foo called with " << s << " and " << sizeof...(Ts) << " ts\n";
}
template<typename... Ts>
void bar(Ts... ts)
{
const std::string s = "hello world";
const auto t = std::make_tuple(ts...);
with_sequence<std::tuple_size_v<decltype(t)>>([&](auto ... i)
{
foo(s, std::get<i.value>(t)...);
});
}
int main()
{
bar(1, 'a', 2.3);
}
Try it live

How to detect std::reference_wrapper in C++ at compile time

Lets say we have some variadic template and need to treat std::reference_wrapper parameters differently.
How can we achieve that?
You can make a trait to tell if a type is reference_wrapper
template<typename T>
struct is_reference_wrapper : false_type {};
template<typename T>
struct is_reference_wrapper<reference_wrapper<T>> : true_type{};
Then you can use it to disambiguate:
template<typename T>
void do_stuff(T&& t, false_type)
{
cout << "Normal: " << t << endl;
}
template<typename T>
void do_stuff(T&& ref, true_type)
{
cout << "Ref: " << ref.get() << endl;
}
template<typename... Ts>
void foo(Ts&&... ts)
{
[[maybe_unused]] int arr[] = {
(do_stuff(forward<Ts>(ts), is_reference_wrapper<decay_t<Ts>>{}), 0)...
};
}
demo

unpacking tuple for method argument

I have a syntax problem with expanding a tuple to its content.
The working code I have:
class Example
{
public:
static void Go( int i, float f)
{
std::cout << "p1: " << i << std::endl;
std::cout << "p2: " << f << std::endl;
}
template <typename T, size_t ... I>
static void Do( T parm )
{
Go( std::get<I>( parm)...);
}
};
int main()
{
using X = std::tuple<int, float>;
Example::Do<X,0,1>( std::make_tuple( 1,2.2)) ;
}
But I want to call the expansion with something like
int main()
{
using X = std::tuple<int, float>;
using IDX = std::std::index_sequence_for<int, float>;
Example::Do<X,IDX>( std::make_tuple( 1,2.2)) ;
}
So I am searching for something like ( which can not compiled... ):
template <typename T, size_t ... I>
static void Do<T, std::index_sequence<I...>>(T parm)
{
Go( std::get<I>( parm)...);
}
Pass the index sequence by value:
template <typename T, size_t... I>
static void Do(T parm, std::index_sequence<I...>)
{
Go(std::get<I>(parm)...);
}
Call the method like this:
Example::Do(std::make_tuple(1, 2.2),
std::index_sequence_for<int, float>{});
The problem is that your std::index_sequence (IDX) is not expanding in the template parameters to what you need:
Example::Do<X, IDX>(std::make_tuple(1, 2.2));
...will not "expand" to:
Example::Do<X, 0, 1>(std::make_tuple(1, 2.2)); // This works
What you need is to let the compiler deduce the template arguments for ...I, to do so change your static method to:
template <typename T, size_t ... I>
static void Do(T parm, std::index_sequence<I...>)
{
Go(std::get<I>(parm)...);
}
And then call it with:
Example::Do(std::make_tuple(1, 2.2), IDX{});
The compiler will automatically deduce the template arguments and call Example::Do<X, 0, 1> as needed.
If you want to be able to call Do without the second arguments, you can add another layer of abstraction in Example:
class Example
{
public:
static void Go(int i, float f) {
std::cout << "p1: " << i << std::endl;
std::cout << "p2: " << f << std::endl;
}
template <typename Tuple>
static void Do(Tuple &&parm) {
_Do(std::forward<Tuple>(parm),
std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>{}>{});
}
private:
template <typename Tuple, size_t... I>
static void _Do(Tuple &&parm, std::index_sequence<I...>) {
Go(std::get<I>(std::forward<Tuple>(parm))...);
}
};
Then:
Example::Do(std::make_tuple(1, 2.2));
Note that the three versions:
Example::Do<X, 0, 1> (std::make_tuple(1, 2.2));
Example::Do(std::make_tuple(1, 2.2), IDX{});
Example::Do(std::make_tuple(1, 2.2));
Will likely results in the same code after compiler optimization (on my machine with clang++-3.7 and -O1, the three assembly files are strictly identical).

How to make sure std::tuple use c++11 move semantics in the following code

I have written a function to apply a function to a std::tuple as below (based on "unpacking" a tuple to call a matching function pointer).
I am concerned that the tuples might be copied around. I have a very basic idea of what move semantics does, and understand concepts like && and rvalue in the string examples commonly found. But I don't know much about how std::forward() and the likes work. And I am not sure how to handle it when there is also packing and variadic programming. (I added a few std::forward and &&'s around and soon get compilation errors.)
Can someone please explain how to make move semantics work for the tuples here? One additional question is, how can I verify (except for visual inspection of code) that move semantic indeed works for the tuples in the code?
Thanks in advance.
#include <tuple>
#include <iostream>
#include <functional>
template<int ...> struct seq {};
template<int N, int ...S> struct gens : gens<N-1, N-1, S...> {};
template<int ...S> struct gens<0, S...>{ typedef seq<S...> type; };
template <typename R, typename Tp, typename ...FArgs>
struct t_app_aux {
template<int ...S>
R static callFunc(std::function<R (FArgs...)> f,Tp t,seq<S...>) {
return f(std::get<S>(t) ...);
}
};
template <typename R, typename Tp, typename ...FArgs>
R t_app(std::function<R (FArgs...)> f, Tp t) {
static_assert(std::tuple_size<Tp>::value == sizeof...(FArgs), "type error: t_app wrong arity");
return t_app_aux<R, Tp, FArgs...>::callFunc(f,t,typename gens<sizeof...(FArgs)>::type());
}
int main(void)
{
std::tuple<int, float, double> t = std::make_tuple(1, 1.2, 5);
std::function<double (int,float,double)> foo1 = [](int x, float y, double z) {
return x + y + z;
};
std::cout << t_app(foo1,t) << std::endl;
}
There are copies with your current implementation: http://ideone.com/cAlorb
I added a type with some log:
struct foo
{
foo() : _value(0) { std::cout << "default foo" << std::endl; }
foo(int value) : _value(value) { std::cout << "int foo" << std::endl; }
foo(const foo& other) : _value(other._value) { std::cout << "copy foo" << std::endl; }
foo(foo&& other) : _value(other._value) { std::cout << "move foo" << std::endl; }
int _value;
};
And also before/after your application:
std::cout << "Function created" << std::endl;
std::cout << t_app(foo1,t) << std::endl;
std::cout << "Function applied" << std::endl;
It gives:
Function created
copy foo
copy foo
7.2
Function applied
So then, to fix this adding forward is done like this:
template <typename R, typename Tp, typename ...FArgs>
struct t_app_aux {
template<int ...S>
R static callFunc(std::function<R (FArgs...)> f, Tp&& t, seq<S...>) {
return f(std::get<S>(std::forward<Tp>(t)) ...);
}
};
template <typename R, typename Tp, typename ...FArgs>
R t_app(std::function<R (FArgs...)> f, Tp&& t)
{
static_assert(std::tuple_size<typename std::remove_reference<Tp>::type>::value == sizeof...(FArgs),
"type error: t_app wrong arity");
return t_app_aux<R, Tp, FArgs...>::callFunc(f, std::forward<Tp>(t), typename gens<sizeof...(FArgs)>::type());
}
As you can see it removes unwanted copies: http://ideone.com/S3wF6x
Function created
7.2
Function applied
The only problem was to handle the static_assert because std::tuple_size was called on a std::tuple<>& and it did not work. I used typename std::remove_reference<Tp>::type but maybe there is a clever and more universal way ?

template template parameter that is counted as one single parameter

In the code below, the class template uses one parameter but the function template uses two if the template argument is a template. This is ok when using type deduction but odd when using explicit template instantiation.
Is is possible to write the template template parameter as one single parameter?
This question is linked to function overload matching template template
#include <iostream>
template <typename T>
struct C
{
C (T i)
{
std::cout << "simple" << std::endl;
}
};
template <template<typename TT> class FF, typename TT>
struct C <FF<TT> > // (1)
{
C (FF<TT> i)
{
std::cout << "template" << std::endl;
}
};
template <typename T>
void F (T i)
{
std::cout << "simple" << std::endl;
}
// two template arguments FF and TT.
// Anyway to write this so that the argument count is one?
template <template<typename TT> class FF, typename TT>
void F (FF<TT> i)
{
std::cout << "template" << std::endl;
}
template <typename T>
struct R
{
T x;
};
int main()
{
R<int> r;
C<R<int> >{r}; // prints 'template', as expected
F<R<int> >(r); // prints 'simple', probably not what you think
F<R,int >(r); // prints 'template' as expected but
}
EDIT:
I came to the conclusion that the question is not a good one because if there where a one parameter syntax, the overload resolution would still pick the wrong function. This comes as a surprise to me but here is the code that proves it (same code as before except one template function overload that changed):
EDIt2: added a further print in the main skipping the explicit template specification.
EDIT3: The code below is nonsense. I made a mistake as #DyP pointed out correctly. I am calling void F(R<R<T>>) in the explicit case and not void F(R<T>) .
#include <iostream>
template <typename T>
struct R
{
T x;
};
template <typename T>
struct C
{
C (T i)
{
std::cout << "simple" << std::endl;
}
};
template <template<typename TT> class FF, typename TT>
struct C <FF<TT> > // (1)
{
C (FF<TT> i)
{
std::cout << "template" << std::endl;
}
};
template <typename T>
void F (R<T> i)
{
std::cout << "template" << i.x << std::endl;
}
template <typename T>
void F (T i)
{
std::cout << "simple" << std::endl;
}
int main()
{
R<int> r;
C<R<int> >{r}; // prints 'template', as expected
F<R<int> >(r); // prints 'simple', probably not the expected overload
F (r); // prints 'template', now overload resolution works. Strange.
}
With SFINAE:
#include <type_traits>
template<class T>
struct is_template_with_one_param
: std::false_type
{};
template<template<class> class TT, class T>
struct is_template_with_one_param< TT<T> >
: std::true_type
{};
#include <iostream>
template <typename T>
typename std::enable_if< not is_template_with_one_param<T>{}, void >::type
F (T i)
{
std::cout << "simple" << std::endl;
}
template <typename T>
typename std::enable_if< is_template_with_one_param<T>{}, void >::type
F (T i)
{
std::cout << "template" << std::endl;
}
usage example:
template <typename T>
struct R
{
T x;
};
int main()
{
F(R<int>{});
F(42);
}
Alternatively, consider Jarod42's suggestion.
Another possible solution:
#include <iostream>
template <typename T>
struct C
{
C (T i)
{
std::cout << "simple" << std::endl;
}
};
template <template<typename TT> class FF, typename TT>
struct C <FF<TT> > // (1)
{
C (FF<TT> i)
{
std::cout << "template" << std::endl;
}
};
template <typename T>
void F (T i)
{
C<T> x(i);
}
template <typename T>
struct R
{
T x;
};
int main()
{
R<int> r;
F(r);
F(4);
}