When we have a function template like this:
template <class T>
void push_back(T&& type)
{
}
It is perfectly legal, to call it like this:
push_back(1);
and like this:
int i = 0;
push_back(i);
But, when I have a template class:
template <class Type>
class List
{
public:
void push_back(Type&& value)
{
}
};
I cannot call it like this:
List<int> list_int;
int i = 42;
list_int.push_back(i);
because I am getting the folllowing:
error: rvalue reference to type 'int' cannot bind to lvalue of type 'int'
Would someone explain to me why, please?
In:
template <class T>
void push_back(T&& type)
T&& type is a forwarding reference, that binds to any value category.
Whereas in:
template <class Type>
class List
{
public:
void push_back(Type&& value)
{
}
};
Type&& value is an r-value reference, that only binds to r-values.
To make List::push_back use forwarding references push_back must be made a function template:
template <class Type>
class List
{
public:
template<class U>
void push_back(U&& value)
{
}
};
Or, in C++20, use auto&& parameter type:
template <class Type>
class List
{
public:
void push_back(auto&& value)
{
}
};
Related
I would like to check if there exist a member function with signature fit to a parameter pack. I began with the known SFINAE concept, while trying to extend it for considering also a parameters pack. But at this point I found that I don't know how to do it.
I try to do something like this:
// Note: T object may have several functions with the name foo, but with different signatures.
// a function foo also can be a template one with variadic parameters pack.
template<typename T, typename...Args>
class HAS_FUNCTION_FOO
{
template<typename U>
static bool test(decltype(&U::foo));
template<typename U>
static float test(...);
public:
static constexpr bool value = std::is_integral<decltype(test<T>(Args...))>::value;
//-------------------------------------------------------------^^^^^^^^^
// how to do it?
};
I would like to use it for declaring specific object at compile time - something like this:
class Bar
{
public:
template<typename T, typename...Args>
void doSomthing(T* p, Args&&...parameters)
{
// get correct object type:
// if T has a function called foo with parameters fits for pack, then declare A, o.w declare B.
using ObjType = typename std::conditional<HAS_FUNCTION_FOO<T, Args>::value, A, B>::type;
// compute
ObjType::doSomthing(p, std::forward<Args>(parameters)...);
}
private:
struct A
{
template<typename T, typename...Args>
static void doSomthing(T* p, Args&&...parameters)
{
p->foo(std::forward<Args>(parameters)...);
}
};
struct B
{
template<typename T, typename...Args>
static void doSomthing(T* p, Args&&...parameters)
{
// do something else
}
};
};
Something like this, perhaps:
template<typename T, typename...Args>
class HAS_FUNCTION_FOO
{
template <typename U>
static std::true_type test(
typename std::enable_if<sizeof(
decltype(std::declval<U>().foo(std::declval<Args>()...))*) != 0>::type*
);
template <typename U>
static std::false_type test(...);
public:
static constexpr bool value = decltype(test<T>(nullptr))::value;
};
Demo
I would like to have a variadic class template to generate one method per type, such that for example a class template like the following:
template <class T, class ... Ts>
class MyClass {
public:
virtual void hello(const T& t) = 0;
};
would make available the methods hello(const double&) and hello(const int&) when instantiated as MyClass<double, int> myclass;
Note that I want the class to be pure abstract, such that a derived class would actually need to do the implementation, e.g.:
class Derived : MyClass<double, int> {
public:
inline void hello(const double& t) override { }
inline void hello(const int& t) override { }
};
This problem is somewhat similar to this one, but I couldn't understand how to adapt it to my case.
EDIT
The recursion inheritance seems to be the right solution for me. How about this more complicated case, where the superclass has more than one method and a template argument is mandatory? Here is what I've tried (but I get error):
template <class MandatoryT, class OptionalT, class... MoreTs>
class MyClass : public MyClass<MandatoryT, MoreTs...> {
public:
virtual ~MyClass() {}
virtual char* goodmorning(const MandatoryT& t) = 0;
virtual bool bye(const MandatoryT& t,
const std::map<std::string,bool>& t2) = 0;
using MyClass<MandatoryT, MoreTs...>::hello;
virtual void hello(const OptionalT& msg) = 0;
};
template <class MandatoryT, class OptionalT>
class MyClass<MandatoryT, OptionalT> {
virtual void processSecondaryMessage(const OptionalT& msg) = 0;
};
template <class MandatoryT>
class MyClass<MandatoryT> {
virtual void processSecondaryMessage() = 0;
}
}
Basically what I want is that the derived class should have one or more types. The first one is used in other methods, while from the second onwards it should be used in hello(). If only one type is provided, an empty hello() is called. But when at least a second type is provided, hello() should use it.
The code above complains that there should be at least two template arguments, because there are "two" ground cases instead of one.
Maybe someone else can do better, but I see only two ways
Recursion inheritance
You can define MyClass recursively as follows
// recursive case
template <typename T, typename ... Ts>
struct MyClass : public MyClass<Ts...>
{
using MyClass<Ts...>::hello;
virtual void hello (const T&) = 0;
};
// ground case
template <typename T>
struct MyClass<T>
{ virtual void hello (const T&) = 0; };
or
variadic inheritance
You can define another class/struct, say MyHello, that declare a
single hello() method, and variadic inherit it from MyClass.
template <typename T>
struct MyHello
{ virtual void hello (const T&) = 0; };
template <typename ... Ts>
struct MyClass : public MyHello<Ts>...
{ };
The recursive example is compatible with type collision (that is: works also when a type is present more time in the list of template arguments MyClass; by example MyClass<int, double, int>).
The variadic inheritance case, unfortunately, isn't.
The following is a full compiling example
#if 1
// recursive case
template <typename T, typename ... Ts>
struct MyClass : public MyClass<Ts...>
{
using MyClass<Ts...>::hello;
virtual void hello (const T&) = 0;
};
// ground case
template <typename T>
struct MyClass<T>
{ virtual void hello (const T&) = 0; };
#else
template <typename T>
struct MyHello
{ virtual void hello (const T&) = 0; };
template <typename ... Ts>
struct MyClass : public MyHello<Ts>...
{ };
#endif
struct Derived : public MyClass<double, int>
{
inline void hello (const double&) override { }
inline void hello (const int&) override { }
};
int main()
{
Derived d;
d.hello(1.0);
d.hello(2);
}
-- EDIT --
The OP asks
how about a more complicated case where MyClass has more than one method and I always need to have one template argument (see edited question)?
From your question I don't understand what do you exactly want.
But supposing you want a pure virtual method, say goodmorning() that receive a MandT (the mandatory type), a pure virtual method hello() for every type following MandT or an hello() without arguments when the list after MandT is empty.
A possible solution is the following
// declaration and groundcase with only mandatory type (other cases
// intecepted by specializations)
template <typename MandT, typename ...>
struct MyClass
{
virtual void hello () = 0;
virtual ~MyClass () {}
virtual char * goodmorning (MandT const &) = 0;
};
// groundcase with a single optional type
template <typename MandT, typename OptT>
struct MyClass<MandT, OptT>
{
virtual void hello (OptT const &) = 0;
virtual ~MyClass () {}
virtual char * goodmorning (MandT const &) = 0;
};
// recursive case
template <typename MandT, typename OptT, typename ... MoreOptTs>
struct MyClass<MandT, OptT, MoreOptTs...>
: public MyClass<MandT, MoreOptTs...>
{
using MyClass<MandT, MoreOptTs...>::hello;
virtual void hello (OptT const &) = 0;
virtual ~MyClass () {}
};
Here the recursion is a little more complicated than before.
In case you instantiate a MyClass with only the mandatory type (by example: MyClass<char>) the main version ("groundcase with only mandatory type") is selected because the two specialization doesn't match (no first optional type).
In case you instantiate a Myclass with one optional type (say MyClass<char, double>) the specialization "groundcase with a single optional type" is selected because is the most specialized version.
In case you instantiate a MyClass with two or more optional type (say MyClass<char, double, int> start recursion (last specialization) until remain an single optional type (so the "groundcase with a single optional type" is selected).
Observe that I've placed the goodmorning() in both ground cases, because you don't need to define it recursively.
The following is a full compiling example
// declaration and groundcase with only mandatory type (other cases
// intecepted by specializations)
template <typename MandT, typename ...>
struct MyClass
{
virtual void hello () = 0;
virtual ~MyClass () {}
virtual char * goodmorning (MandT const &) = 0;
};
// groundcase with a single optional type
template <typename MandT, typename OptT>
struct MyClass<MandT, OptT>
{
virtual void hello (OptT const &) = 0;
virtual ~MyClass () {}
virtual char * goodmorning (MandT const &) = 0;
};
// recursive case
template <typename MandT, typename OptT, typename ... MoreOptTs>
struct MyClass<MandT, OptT, MoreOptTs...>
: public MyClass<MandT, MoreOptTs...>
{
using MyClass<MandT, MoreOptTs...>::hello;
virtual void hello (OptT const &) = 0;
virtual ~MyClass () {}
};
struct Derived0 : public MyClass<char>
{
void hello () override { }
char * goodmorning (char const &) override
{ return nullptr; }
};
struct Derived1 : public MyClass<char, double>
{
void hello (double const &) override { }
char * goodmorning (char const &) override
{ return nullptr; }
};
struct Derived2 : public MyClass<char, double, int>
{
void hello (double const &) override { }
void hello (int const &) override { }
char * goodmorning (char const &) override
{ return nullptr; }
};
int main()
{
Derived0 d0;
Derived1 d1;
Derived2 d2;
d0.hello();
d0.goodmorning('a');
d1.hello(1.2);
d1.goodmorning('b');
d2.hello(3.4);
d2.hello(5);
d2.goodmorning('c');
}
I am trying to create class deriving from variadic template. Here is the code:
struct Some { };
template < class Base, class T >
struct Feature
{
protected:
void DoStuff(T& t) { }
};
template < class T, class ... Ts >
struct MultiFeature
: public Feature< T, Ts >...
{
};
class TestFeature
: public MultiFeature< Some, std::int16_t, std::string >
{
public:
void TestDoStuff()
{
std::int16_t i;
DoStuff(i);
}
};
Feature should be a simple wrapper around some basic type (in this case, integer and string), providing some functionality to class deriving from it. MultiFeature is used so that I do not have to derive from Feature< std::int16_t >, Feature< std::string >.
As far as I understand, there should be no ambiguity in this case, because there are two different DoStuff functions, each taking different parameter type, however VS2017 complains about ambiguous access. Is this correct behavior? If so, is there any simple workaround around this problem?
EDIT
It seems that compiler is right here, however in this answer, suggested workaround for this is to bring base class member functions into scope with using (Ambiguous access to base class template member function). Is it somehow possible to do this for variadic template base class?
It seems that compiler is right here, however in this answer, suggested workaround for this is to bring base class member functions into scope with using (Ambiguous access to base class template member function). Is it somehow possible to do this for variadic template base class?
If you can use C++17, it's trivially simple
template <typename T, typename ... Ts>
struct MultiFeature : public Feature<T, Ts>...
{
using Feature<T, Ts>::DoStuff...;
};
Unfortunately the variadic using is introduced in C++17 so, in C++11 and C++14, the best I can imagine is a MultiFeature recursive definition
// ground case: a fake DoStuff to abilitate following using
template <typename T, typename ... Ts>
struct MultiFeature
{ void DoStuff () { } };
// recursion case
template <typename T, typename T0, typename ... Ts>
struct MultiFeature<T, T0, Ts...>
: public Feature<T, T0>, public MultiFeature<T, Ts...>
{
using Feature<T, T0>::DoStuff;
using MultiFeature<T, Ts...>::DoStuff;
};
The following is a full compiling example (with both cases)
struct Some { };
template <typename, typename T>
struct Feature
{
protected:
void DoStuff (T &) { }
};
#if 0
template <typename T, typename ... Ts>
struct MultiFeature : public Feature<T, Ts>...
{
using Feature<T, Ts>::DoStuff...;
};
#else
// ground case: a fake DoStuff to abilitate following using
template <typename T, typename ... Ts>
struct MultiFeature
{ void DoStuff () { } };
// recursion case
template <typename T, typename T0, typename ... Ts>
struct MultiFeature<T, T0, Ts...>
: public Feature<T, T0>, public MultiFeature<T, Ts...>
{
using Feature<T, T0>::DoStuff;
using MultiFeature<T, Ts...>::DoStuff;
};
#endif
struct TestFeature
: public MultiFeature<Some, short, int, long, long long>
{
void TestDoStuff ()
{ int a{}; DoStuff(a); }
};
int main ()
{
TestFeature tf;
}
The following is a mockup code that I wrote to experiment with trailing return types in a CRTP setup.
#include <iostream>
#include <memory>
#include <utility>
using namespace std;
struct t_aspect{
struct t_param1 {};
};
// Generic Selector
template <typename t_detail>
struct Select;
template <>
struct Select<t_aspect::t_param1> {
using typeof = t_aspect::t_param1;
};
//Base CRTP class
template<typename dclas>
class CrtpB
{
public:
template<typename T1>
auto func1() -> // What should be here?
{
return(static_cast<dclas*>(this)->func1<T1>());
}
};
//Derived CRTP class
class CrtpD : public CrtpB<CrtpD>
{
private:
uint32_t param1 = 0;
private:
auto func1(const t_aspect::t_param1&) -> uint32_t
{
return(param1);
}
public:
static auto create() -> unique_ptr<CrtpB>
{
return(unique_ptr<CrtpD>(new CrtpD));
}
template<typename T1>
auto func1() -> decltype(func1(typename Select<T1>::typeof()))
{
return(func1(typename Select<T1>::typeof()));
}
};
int main()
{
auto crtp = CrtpD::create();
auto parm = crtp->func1<t_aspect::t_param1>();
return 0;
}
I would like some help in deciphering what should be the trailing return type of func1 in CrtpB.
I have tried using
decltype(static_cast<dclas*>(this)->func1<T1>())
but this does not work. I have also tried writing a helper function based on a solution found in Inferring return type of templated member functions in CRTP.
template <typename D, typename T>
struct Helpr {
typedef decltype(static_cast<D*>(0)->func1<T>()) type;
};
But this does not work either.
dclas is an incomplete type when the base class is instantiated. You need to do two things to make this work:
Defer the checking of the type of func1<T1>() until the type is complete
Use the template keyword on the dependent expression so that the template definition is parsed correctly:
We can do this by adding a layer of indirection:
namespace detail {
template <class T, class Func1Arg>
struct func1_t {
using type = decltype(std::declval<T>().template func1<Func1Arg>());
};
};
Then you use this trait as the trailing return type:
template<typename T1>
auto func1() -> typename detail::func1_t<dclas,T1>::type
{
return(static_cast<dclas*>(this)->template func1<T1>());
}
I want to try to do a generic getter by using C++11, but I have an issue if I try to define the generic getter outside the template class.
This code works fine
template <typename T>
class test
{
public:
........
//generic getter
template <typename F>
auto getter_elem_member(F fun)->decltype(fun())
{ return elem.fun(); }
private
T elem;
};
but if I try the code in this way:
template <typename T>
class test
{
public:
........
//generic getter
template <typename F>
auto getter_elem_member(F fun)->decltype(fun());
private
T elem;
};
template <typename T>
template <typename F>
auto test<T>::getter_elem_member(F fun)->decltype(fun())
{ return elem.fun(); }
I obtain the error "Member declaration not found".
Where am I wrong?
Thanks in advance for any suggestions
I am doing exercises with new features, here a example that works (unless a warning)
#include <iostream>
#include <string>
template <typename T>
class test
{
public:
//costruttori - distruttori
test(){}
~test(){}
public:
//generic getter
template <typename F>
auto getter_elem_member(F fun)
{ return (elem.*fun)(); }
//generic getter
template <typename F>
auto getter_elem_member2(F fun)->decltype(fun())
{ return fun(); }
private:
T elem;
};
struct A
{
std::string print(){return "ciao";}
static std::string print2(){return "ciao";}
};
int main()
{
test<A> test1;
std::cout << test1.getter_elem_member(&A::print) << std::endl;
std::cout << test1.getter_elem_member2(A::print2) << std::endl;
}
If you're trying to make a proxy function which calls a member function of a private member variable through a member function pointer, I don't think you need decltype at all.
// Member function pointer version
template <class Ret>
Ret getter_elem_member(Ret (T::*fun)())
{ return (elem.*fun)(); }
// Generic function object version
template <class F>
auto getter_elem_member(F fun) -> decltype(fun())
{ return fun(); }
If a function pointer is given, the first one will be called. For other callable types, the second one will be called.
The second one, which is for a generic callable object, seems unnecessary. Since you can't access the private member in fun anyway, so it's better calling fun() outside than passing it and making your class call it.
It appears that you're trying to use a template function-like paradigm.
You should use std::function to do this. If not, you can probably get along with some sort of templated function pointer to do this.