Let's say I have this code:
class BaseObject
{
public:
virtual void OnDestroy() {}
};
template <typename T>
struct myArrayDeleter
{
void operator()(T *p, std::size_t count)
{
for(std::size_t i = 0; i < count; i++)
{
static_cast<BaseObject*>((void*)(int(p) + sizeof(T) * i))->OnDestroy();
}
delete [] p;
}
};
And let's assume that it works as intended (it's a simplified version, written now without the check but basically you know what this code should do).
With this part I don't have a problem. However, check this out:
class AActor
: public BaseObject
{
public:
virtual void OnDestroy() override
{
// some code here
}
};
template <typename T>
class SimplifiedHolder
{
protected:
std::shared_ptr<T> m_shared;
std::size_t m_size;
public:
// Some not important code here
// WE ASSUME HERE THAT IT ALWAYS HOLDS ARRAY
// sizeOfArray always > 1
template <typename U>
SimplifiedHolder(U *ptr, std::size_t sizeOfArray)
: m_size(sizeOfArray)
{
m_shared = std::shared_ptr<T>(ptr,
std::bind(&myArrayDeleter<U>(), std::placeholders::_1, m_size));
}
// And now as we initialize our shared_ptr with template
// we can check if it is exactly of type "U"
template <typename U>
bool IsExactlyOfType()
{
if(!m_shared)
return false;
return ((void*)std::get_deleter<myArrayDeleter<U>>(m_shared)) != nullptr;
}
};
However, the method IsExactlyOfType isn't working. That's because I initialized shared_ptr with std::bind. std::get_deleter always returns nullptr because the wrong type is specified in the template. I don't know what type to pass. I tried also with non-array code in which myDeleter is a functor with only one argument and it works perfectly with code like this:
template <typename U>
bool IsExactlyOfType()
{
if(!m_shared)
return false;
return ((void*)std::get_deleter<myDeleter<U>>(m_shared) != nullptr;
}
I know I could go with typeid(U) == typeid(*m_shared.get()) but this is not what I want. I have much more complicated code and in that case only this method is good.
Can a more experienced programmer tell me what type to specify to std::get_deleter?
It turned out that compiler wasn't translating decltype correctly. I tried to get deleter immediately after initializing shared_ptr and it worked. However the same decltype in function was generating slightly other type. I checked it in debugger and it generated this results:
In constructor:
std::_Binder<std::_Unforced,grim::impl::TObjectArrayDeleter<APlayer>,std::_Ph<1> const &,unsigned int &> &
In function:
std::_Binder<std::_Unforced,grim::impl::TObjectArrayDeleter<APlayer>,std::_Ph<1> const &,unsigned int const &> *
Take a look at the end - it appended additional const. I needed to change it manually, so now my code looks like this:
using D = std::_Binder<std::_Unforced,grim::impl::TObjectArrayDeleter<U>,
std::_Ph<1> const &,unsigned int &>;
return ((void*)std::get_deleter<D>(m_shared)) != nullptr;
Related
I've been trying to expand a non value parameter pack recently in C++. Is this possible? And if it's not, why?
I mean, as you can see, in the line with the comment //, given a parameter pack for the TypeMap class, how can I call addType<T>() with each type of the parameter pack? Thanks in advance!
template <typename... T>
class TypeMap
{
using vari_cmps = std::variant<T*...>;
private:
template<typename Type>
void addType()
{
typemap[typeid(Type).name()] = std::make_unique<Type>(0).get();
}
public:
std::map<const char*, vari_cmps> typemap{};
TypeMap()
{
(addType<T,...>()); // Idk how to use this in order to make it work
}
~TypeMap()
{
typemap.clear();
}
};
As #HolyBlackCat has already answered in the comments, you can expand it like this:
TypeMap() {
(addType<T>(), ...);
}
If T is std::string, int, float this would expand to:
TypeMap() {
(addType<std::string>(), addType<int>(), addType<float>());
}
There are however a few more issues in this code-snippet:
1. addType()
addType() will not work as you'd expect, due to the unique_ptr deleteing your object after you put it into the map.
.get() only retrieves the pointer that the unique_ptr manages but does not transfer ownership, so the unique_ptr will still delete the pointed-to object once it gets out of scope, leaving a dangling pointer in your map.
so your addType() is roughly equivalent to:
template<typename Type>
void addType() {
Type* tptr = new Type(0); // unique pointer constructs object
typemap[typeid(Type).name()] = tptr; // insert pointer value of unique pointer
delete tptr; // unique pointer destructs
}
You could fix this by releasing the unique_ptr after inserting its value into the map & then cleaning it up in the destructor:
template<typename Type>
void addType() {
auto ptr = std::make_unique<Type>(0);
typemap[typeid(Type).name()] = ptr.get();
ptr.release(); // now unique_ptr won't delete the object
}
~TypeMap() {
// cleanup all pointers
for(auto& [name, ptrVariant] : typemap)
std::visit([](auto ptr) { delete ptr; }, ptrVariant);
}
2. Consider using std::type_index instead of const char* as map key
std::type_info::name() returns an implementation-defined name for the given type, so you have no guarantee that you will get an unique name for a given type.
Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given; in particular, the returned string can be identical for several types and change between invocations of the same program.
std::type_index on the other hand is build specifically for this purpose - using types as keys - and comes with all comparison operators & a std::hash specialization, so you can use it with std::map & std::unordered_map out of the box.
e.g.:
template <class... T>
class TypeMap
{
using vari_cmps = std::variant<T*...>;
private:
template<typename Type>
void addType()
{
typemap[std::type_index(typeid(Type))] = /* something */;
}
public:
std::map<std::type_index, vari_cmps> typemap{};
TypeMap() { /* ... */ }
~TypeMap() { /* ... */ }
template<class U>
U* get() {
auto it = typemap.find(std::type_index(typeid(U)));
return std::get<U*>(it->second);
}
};
Consider using std::tuple
std::tuple is basically built for this task, storing a list of arbitrary types:
e.g.:
template <class... T>
class TypeMap
{
private:
std::tuple<std::unique_ptr<T>...> values;
public:
TypeMap() : values(std::make_unique<T>(0)...) {
}
template<class U> requires (std::is_same_v<U, T> || ...)
U& get() { return *std::get<std::unique_ptr<U>>(values); }
template<class U> requires (std::is_same_v<U, T> || ...)
U const& get() const { return *std::get<std::unique_ptr<U>>(values); }
};
usage:
TypeMap<int, double, float> tm;
tm.get<int>() = 12;
If you want you can also store T's directly in the tuple, avoiding the additional allocations.
I am working in a memory constrained embedded environment where malloc/free new/delete are not advisable, and I'm trying to use the std::function pattern to register callbacks. I do not have access to any of the STL methods in my target code so I'm in the unfortunate situation of having to replicate some of the STL functionality myself. Function pointers are not an option for me due to the necessity for callers to have captures.
For instance, I wish to declare a class Mailbox where an onChange event can be registered
class Mailbox {
std::function<void(int,int)> onChange;
};
That way, callers can register a lambda onChange handler that could capture this or other variables that matter for handling the event.
Since this is part of an API, I want to give the users of Mailbox maximim flexibility to either provide a function pointer, a lambda or a functor.
I have managed to find a great implementation of a std::function that appears to be exceptionally low-overhead and has exactly what I need except that it involves dynamic memory.
If you look at the following code, dynamic memory is used in exactly one place, and it appears fully scoped to the object being templated, suggesting to me that its size ought to be known at compile-time.
Can anyone help me understand how to refactor this implementation so that it is fully static and removes the use of new/malloc? I'm having trouble understanding why the size of CallableT wouldn't be calculable at compile-time.
Code below (not for the faint of heart). Note, it uses make_unique / unique_ptr but those can easily be substituted with new and * and I have tested that use case successfully.
#include <iostream>
#include <memory>
#include <cassert>
using namespace std;
template <typename T>
class naive_function;
template <typename ReturnValue, typename... Args>
class naive_function<ReturnValue(Args...)> {
public:
template <typename T>
naive_function& operator=(T t) {
callable_ = std::make_unique<CallableT<T>>(t);
return *this;
}
ReturnValue operator()(Args... args) const {
assert(callable_);
return callable_->Invoke(args...);
}
private:
class ICallable {
public:
virtual ~ICallable() = default;
virtual ReturnValue Invoke(Args...) = 0;
};
template <typename T>
class CallableT : public ICallable {
public:
CallableT(const T& t)
: t_(t) {
}
~CallableT() override = default;
ReturnValue Invoke(Args... args) override {
return t_(args...);
}
private:
T t_;
};
std::unique_ptr<ICallable> callable_;
};
void func() {
cout << "func" << endl;
}
struct functor {
void operator()() {
cout << "functor" << endl;
}
};
int main() {
naive_function<void()> f;
f = func;
f();
f = functor();
f();
f = []() { cout << "lambda" << endl; };
f();
}
Edit: added clarification on STL
The name for what you're looking for is "in-place function". At least one very good implementation exists today:
sg14::inplace_function<R(A...), Size, Align>
There is also tj::inplace_any<Size, Align>, if you need/want the semantics of any.
Let me preface this answer by saying that storing a general callable faces an interesting choice in terms of memory management. Yes, we can deduce the size of any callable at compile time but we can not store any callable into the same object without memory management. That's because our own object needs to have size independently of the callables its supposed to store but those can be arbitrarily big.
To put this reasoning into one sentence: The layout of our class (and its interface) needs to be compiled without knowledge about all of the callers.
This leaves us with essentially 3 choices
We embrace memory management. We dynamically copy the callable and properly manage that memory through means of unique pointer (std or boost), or through custom calls to new and delete. This is what the original code you found does and is also done by std::function.
We only allow certain callables. We create some custom storage inside our object to hold some forms of callables. This storage has a pre-determined size and we reject any callable given that can not adhere to this requirement (e.g. by a static_assert). Note that this does not necessarily restrict the set of possible callers. Instead, any user of the interface could set up a proxy-class holding merely a pointer but forwarding the call operator. We could even offer such a proxy class ourselves as part of the library. But this does nothing more than shifting the point of allocation from inside the function implementation to outside. It's still worth a try, and #radosław-cybulski comes closest to this in his answer.
We don't do memory management. We could design our interface in a way that it deliberately refuses to take ownership of the callable given to it. This way, we don't need to to memory management and this part is completely up to our caller. This is what I will give code for below. It is not a drop-in replacement for std::function but the only way I see to have a generic, allocation-free, copiable type for the purpose you inteded it.
And here is the code for possibility 3, completely without allocation and fully self-contained (does not need any library import)
template<typename>
class FunctionReference;
namespace detail {
template<typename T>
static T& forward(T& t) { return t; }
template<typename T>
static T&& forward(T&& t) { return static_cast<T&&>(t); }
template<typename C, typename R, typename... Args>
constexpr auto get_call(R (C::* o)(Args...)) // We take the argument for sfinae
-> typename FunctionReference<R(Args...)>::ptr_t {
return [](void* t, Args... args) { return (static_cast<C*>(t)->operator())(forward<Args>(args)...); };
}
template<typename C, typename R, typename... Args>
constexpr auto get_call(R (C::* o)(Args...) const) // We take the argument for sfinae
-> typename FunctionReference<R(Args...)>::ptr_t {
return [](void* t, Args... args) { return (static_cast<const C*>(t)->operator())(forward<Args>(args)...); };
}
template<typename R, typename... Args>
constexpr auto expand_call(R (*)(Args...))
-> typename FunctionReference<R(Args...)>::ptr_t {
return [](void* t, Args... args) { return (static_cast<R (*)(Args...)>(t))(forward<Args>(args)...); };
}
}
template<typename R, typename... Args>
class FunctionReference<R(Args...)> {
public:
using signature_t = R(Args...);
using ptr_t = R(*)(void*, Args...);
private:
void* self;
ptr_t function;
public:
template<typename C>
FunctionReference(C* c) : // Pointer to embrace that we do not manage this object
self(c),
function(detail::get_call(&C::operator()))
{ }
using rawfn_ptr_t = R (*)(Args...);
FunctionReference(rawfn_ptr_t fnptr) :
self(fnptr),
function(detail::expand_call(fnptr))
{ }
R operator()(Args... args) {
return function(self, detail::forward<Args>(args)...);
}
};
For seeing how this then works in action, go to https://godbolt.org/g/6mKoca
Try this:
template <class A> class naive_function;
template <typename ReturnValue, typename... Args>
class naive_function<ReturnValue(Args...)> {
public:
naive_function() { }
template <typename T>
naive_function(T t) : set_(true) {
assert(sizeof(CallableT<T>) <= sizeof(callable_));
new (_get()) CallableT<T>(t);
}
template <typename T>
naive_function(T *ptr, ReturnValue(T::*t)(Args...)) : set_(true) {
assert(sizeof(CallableT<T>) <= sizeof(callable_));
new (_get()) CallableT<T>(ptr, t);
}
naive_function(const naive_function &c) : set_(c.set_) {
if (c.set_) c._get()->Copy(&callable_);
}
~naive_function() {
if (set_) _get()->~ICallable();
}
naive_function &operator = (const naive_function &c) {
if (this != &c) {
if (set_) _get()->~ICallable();
if (c.set_) {
set_ = true;
c._get()->Copy(&callable_);
}
else
set_ = false;
}
return *this;
}
ReturnValue operator()(Args... args) const {
return _get()->Invoke(args...);
}
ReturnValue operator()(Args... args) {
return _get()->Invoke(args...);
}
private:
class ICallable {
public:
virtual ~ICallable() = default;
virtual ReturnValue Invoke(Args...) = 0;
virtual void Copy(void *dst) const = 0;
};
ICallable *_get() {
return ((ICallable*)&callable_);
}
const ICallable *_get() const { return ((const ICallable*)&callable_); }
template <typename T>
class CallableT : public ICallable {
public:
CallableT(const T& t)
: t_(t) {
}
~CallableT() override = default;
ReturnValue Invoke(Args... args) override {
return t_(std::forward<ARGS>(args)...);
}
void Copy(void *dst) const override {
new (dst) CallableT(*this);
}
private:
T t_;
};
template <typename T>
class CallableT<ReturnValue(T::*)(Args...)> : public ICallable {
public:
CallableT(T *ptr, ReturnValue(T::*)(Args...))
: ptr_(ptr), t_(t) {
}
~CallableT() override = default;
ReturnValue Invoke(Args... args) override {
return (ptr_->*t_)(std::forward<ARGS>(args)...);
}
void Copy(void *dst) const override {
new (dst) CallableT(*this);
}
private:
T *ptr_;
ReturnValue(T::*t_)(Args...);
};
static constexpr size_t size() {
auto f = []()->void {};
return std::max(
sizeof(CallableT<void(*)()>),
std::max(
sizeof(CallableT<decltype(f)>),
sizeof(CallableT<void (CallableT<void(*)()>::*)()>)
)
);
};
typedef unsigned char callable_array[size()];
typename std::aligned_union<0, callable_array, CallableT<void(*)()>, CallableT<void (CallableT<void(*)()>::*)()>>::type callable_;
bool set_ = false;
};
Keep in mind, that sort of tricks tend to be slightly fragile.
In this case to avoid memory allocation i used unsigned char[] array of assumed max size - max of CallableT with pointer to function, pointer to member function and lambda object. Types of pointer to function and member function dont matter, as standard guarantees, that for all types those pointers will have the same size. Lambda should be pointer to object, but if for some reason isnt and it's size will change depending on lambda types, then you're out of luck.
First callable_ is initialized with placement new and correct CallableT type. Then, when you try to call, i use beginning of callable_ as pointer to ICallable. This all is standard safe.
Keep in mind, that you copy naive_function object, it's template argument T's copy operator is NOT called.
UPDATE: some improvements (at least try to force alignment) + addition of copying constructor / copy assignment.
My attempt to run the solution given Here, encountered with some issues. After fixing them, seems to work fine.
Will be happy for any review as I am not a c++ expert!
Issues and fixes:
error: lambda expression in an unevaluated operand.
removed the decltype. ( was not present in original code so I guess its safe(???)
using aligned_t = detail::aligned_union<0,
CallableT<void(*)()>,
//CallableT<decltype([]()->void {})>,
CallableT<void (CallableT<void(*)()>::*)()>
>;
Under C++11, errors in code block:
error: fields must have a constant size: 'variable length array in structure' extension will never be supported
error: 'aligned' attribute requires integer constant
error: constexpr variable 'alignment_value' must be initialized by a constant expression
(Note: this code is replacing std::aligned_union)
namespace detail {
template <size_t Len, class... Types>
struct aligned_union {
static constexpr size_t alignment_value = std::max({alignof(Types)...}); // ERROR HERE C++11
struct type {
alignas(alignment_value) char _s[std::max({Len, sizeof(Types)...})]; // ERROR HERE C++11
};
};
}
Used 'external' help from ETLCPP - which has support for embedded, file: largest.h.
Error block was replaced with :
#include"etl/largest.h"
template<typename ...Types>
using largest_t = typename etl::largest_type<Types...>::type;
namespace detail {
template <size_t Len, class... Types>
struct aligned_union {
static constexpr size_t alignment_value = etl::largest_alignment<Types...>::value; //std::max({alignof(Types)...});
struct type {
alignas(alignment_value) char _s[sizeof(largest_t<Types...>)]; //[std::max({Len, sizeof(Types)...})];
};
};
}
Looked redundant, removed:
//static constexpr size_t size() {
// auto f = []()->void {};
// return std::max(
// sizeof(CallableT<void(*)()>),
// std::max(
// sizeof(CallableT<decltype(f)>),
// sizeof(CallableT<void (CallableT<void(*)()>::*)()>)
// )
// );
//};
replaced std::forward with etl::forward file: utility.h
Had anew ,and delete errors : Undefined symbol operator delete
(void)*
So added ( I never allocate.. ):
// Define placement new if no new header is available
inline void* operator new(size_t, void* p) { return p; }
inline void* operator new[](size_t, void* p) { return p; }
inline void operator delete(void*, void*) {}
inline void operator delete[](void*, void*) {}
inline void operator delete[](void*) {}
Still getting a warning thought (???):
: warning: replacement function 'operator delete' cannot be declared 'inline' [-Winline-new-delete]
inline void operator delete(void* ) {}
Linker error:
Error: L6218E: Undefined symbol __cxa_pure_virtual ).
Probably because of virtual distractor : (ref)
virtual ~ICallable() = default;
Had to add this : ( any other solution ???)
extern "C" void __cxa_pure_virtual() { while (1); }
I am using a class factory to create objects dynamically. I used this answer for its simplicity (and because I am using Qt).
But now I realize I must add an argument to my constructor
Item(bool newItem /* = true*/);
instead of
Item();
for the code in the referred answer:
template <typename T>
class ClassFactory
{
public:
template <typename TDerived>
void registerType(QString shape)
{
_createFuncs[shape] = &createFunc<TDerived>;
}
T* create(QString shape)
{
typename QMap<QString, PCreateFunc>::const_iterator it = _createFuncs.find(shape);
if (it != _createFuncs.end())
{
return it.value()();
}
return NULL;
}
private:
template <typename TDerived>
static T* createFunc()
{
return new TDerived();
}
typedef T* (*PCreateFunc)();
QMap<QString, PCreateFunc> _createFuncs;
};
I registered the class
classFactory.registerType <Type1_Item> ("type1");
when needed, I called
Item* item = classFactory.create("type1");
I am trying to add an additional argument in the class factory, to represent the constructor argument, but my attempts all result in error.
Why do I need it : simple case:
create a new object - sets defaults; for certain objects, it requires an open file dialog since data has to be loaded from a file.
load an object - fills data, including the filename for objects that contain file info
To be able to call the "load" function, an object must exist - which means that if I create a new object, I will trigger an open file dialog even though I do not need it.
The work around that I see is, to have a constructor followed by a setup function. But... that means constructing an object always requires a 2-function call, which seems like bad design.
that is why I am looking for a way to register and call the classes using simple calls like
classFactory.registerType <Type1_Item> ("type1", bool);
Item* item = classFactory.create("type1", true);
Is it possible, and how can I do it ?
The one way I can think of involves requiring that the arguments match exactly. First, we're going to store our functions using boost::any. This is because they may have different types, so we need a heterogenous container:
QMap<QString, boost::any> _createFuncs;
Our register function will create a specific function pointer to store in said any:
template <typename TDerived, typename... T>
void registerType(QString shape)
{
_createFuncs[shape] = &createFunc<TDerived, T...>;
}
where createFunc now takes extra arguments:
template <typename TDerived, typename... Args>
static T* createFunc(Args... args)
{
return new TDerived(args...);
}
The key is what we do on the creation side. We need to check to see if the any we have stored for the particular type is the right type:
template <typename... Args>
T* create(QString shape, Args... args)
{
using FPtr = T*(*)(Args...);
auto it = _createFuncs.find(shape);
if (it != _createFuncs.end())
{
// ok, it points to some any. is it the right any?
FPtr* fptr = boost::any_cast<FPtr>(&it.value());
if (fptr) {
return (*fptr)(args...);
}
// alternatively to the above, we can have createFunc
// throw bad_any_cast if you pass the wrong arguments
// which could be a loud, explicit failure rather than
// a silent one
return boost::any_cast<FPtr>(it.value())(args...);
}
return nullptr;
}
That will allow this to work:
classFactory.registerType<Item, bool>("type1");
^^^^^^
arg list
Item* item = classFactory.create("type1", true);
Item* item2 = classFactory.create<bool>("type1", 1);
But this will fail, since the any takes a bool, not an int:
Item* item3 = classFactory.create("type1", 1);
#Barry's answer is more than complete. However, if you are just interested in a simplified factory that can construct objects that have constructors taking different parameters, you can do something like:
// Factory method for classes having constructors
// that take an arbitary number of parameters
#include <memory>
class Factory
{
public:
template<typename T, typename... Params>
static std::unique_ptr<T> create(Params... params)
{
return std::make_unique<T>(params...);
}
};
struct Foo
{
Foo(int) {};
};
struct Bar
{
Bar(bool, double) {};
};
int main()
{
std::shared_ptr<Foo> foo = Factory::create<Foo>(42);
std::shared_ptr<Bar> bar = Factory::create<Bar>(true, 42.5);
}
Note that I used smart pointers here, so you don't need to keep track of new/deletes anymore.
You may use this modified version
template <typename T, typename ... Ts>
class ClassFactory
{
public:
template <typename TDerived>
void registerType(QString shape)
{
_createFuncs[shape] = &createFunc<TDerived>;
}
T* create(QString shape, Ts... args)
{
typename QMap<QString, PCreateFunc>::const_iterator it = _createFuncs.find(shape);
if (it != _createFuncs.end())
{
return it.value()(args...);
}
return nullptr;
}
private:
template <typename TDerived>
static T* createFunc(Ts... args)
{
return new TDerived(args);
}
typedef T* (*PCreateFunc)(Ts...);
QMap<QString, PCreateFunc> _createFuncs;
};
And use it
ClassFactory<Item, bool> classFactory;
classFactory.registerType <Type1_Item> ("type1");
Item* item = classFactory.create("type1", true);
If all the objects have the same parameter types (here a bool), just change the create function like this:
T* create(QString shape, bool param) //modified
{
typename QMap<QString, PCreateFunc>::const_iterator it = _createFuncs.find(shape);
if (it != _createFuncs.end())
{
return it.value()(param); //modified
}
return NULL;
}
And change createFunc also:
static T* createFunc(bool param)
{
return new TDerived(param);
}
typedef T* (*PCreateFunc)(bool);
I've done this using C++11 parameter packs:
// pack.cc
#include <utility>
template<class T, typename... P>
T * create(P&&... params)
{
return new T(std::forward<P>(params)...);
}
class X
{
public:
X() {}
};
class Y
{
public:
Y(int) {}
};
int main()
{
X * x = create<X>();
Y * y = create<Y>(1);
delete x;
delete y;
}
Compile this example g++ -std=c++11 -o pack pack.cc
Hello I'm having problems with partial specialization. What I want to do is have a class that has a template member function that will interpret a given value to one specified by the user. For instance the class name is Value and here is a snippet of what I want to do:
int *ptr1 = new int;
*ptr1 = 10;
Value val1 = ptr1;
int *ptr2 = val1.getValue<int*>();
Value val2 = 1;
int testVal = val2.getValue<int>();
Here is how I implemented such class:
struct Value {
Value(void *p) : val1(p){}
Value(int i) : val2(i){}
template<typename T>
T getValue();
void *val1;
int val2;
};
template<typename T>
T* Value::getValue<T*>() {
return reinterpret_cast<T*>(val1);
}
template<>
int Value::getValue<int>() {
return val2;
}
When I compile I'm getting the following error:
error C2768: 'Value::getValue' : illegal use of explicit template
arguments
Basically its complaining about the pointer template part of the code:
template<typename T>
T* Value::getValue<T*>() {
return reinterpret_cast<T*>(val1);
}
I know this problem can be implemented with a simple union, But this code is a stripped down version of a bigger code.
Does someone know what the problem could be? What I would like to do is separate one code for when using pointers and other for when not using pointers . I'm really stuck and I always investigate instead of asking, but I haven't found any good info about it.
Function templates cannot be partially specialised, but most of the time, you can use the delegate-to-class trick. In you example it would be like this:
struct Value {
template<typename T>
T getValue() {
return Impl_getValue<T>::call(*this);
}
};
template <typename T>
struct Impl_getValue
{
static T call(Value &v) {
//primary template implementation
}
};
template <typename T>
struct Impl_getValue<T*>
{
static T* call(Value &v) {
return reinterpret_cast<T*>(v.val1);
}
};
Please, consider the code below:
template<typename T>
bool function1(T some_var) { return true; }
template <typename T>
bool (*function2())(T) {
return function1<T>;
}
void function3( bool(*input_function)(char) ) {}
If I call
function3(function2<char>());
it is ok. But if I call
function3(function2());
compiler gives the error that it is not able to deduction the argument for template.
Could you, please, advise (give an idea) how to rewrite function1 and/or function2 (may be, fundamentally to rewrite using classes) to make it ok?
* Added *
I am trying to do something simple like lambda expressions in Boost.LambdaLib (may be, I am on a wrong way):
sort(some_vector.begin(), some_vector.end(), _1 < _2)
I did this:
template<typename T>
bool my_func_greater (const T& a, const T& b) {
return a > b;
}
template<typename T>
bool my_func_lesser (const T& a, const T& b) {
return b > a;
}
class my_comparing {
public:
int value;
my_comparing(int value) : value(value) {}
template <typename T>
bool (*operator<(const my_comparing& another) const)(const T&, const T&) {
if (this->value == 1 && another.value == 2) {
return my_func_greater<T>;
} else {
return my_func_greater<T>;
}
}
};
const my_comparing& m_1 = my_comparing(1);
const my_comparing& m_2 = my_comparing(2);
It works:
sort(a, a + 5, m_1.operator< <int>(m_2));
But I want that it doesn't require template argument as in LambdaLib.
Deduction from return type is not possible. So function2 can't be deduced from what return type you expect.
It is however possible to deduce cast operator. So you can replace function2 with a helper structure like: Unfortunately there is no standard syntax for declaring cast operator to function pointer without typedef and type deduction won't work through typedef. Following definition works in some compilers (works in G++ 4.5, does not work in VC++ 9):
struct function2 {
template <typename T>
(*operator bool())(T) {
return function1<T>;
}
};
(see also C++ Conversion operator for converting to function pointer).
The call should than still look the same.
Note: C++11 introduces alternative typedef syntax which can be templated. It would be like:
struct function2 {
template <typename T>
using ftype = bool(*)(T);
template <typename T>
operator ftype<T>() {
return function1<T>;
}
};
but I have neither G++ 4.7 nor VC++ 10 at hand, so I can't test whether it actually works.
Ad Added:
The trick in Boost.Lambda is that it does not return functions, but functors. And functors can be class templates. So you'd have:
template<typename T>
bool function1(T some_var) { return true; }
class function2 {
template <typename T>
bool operator()(T t) {
function1<T>;
}
};
template <typename F>
void function3( F input_function ) { ... input_function(something) ... }
Now you can write:
function3(function2);
and it's going to resolve the template inside function3. All STL takes functors as templates, so that's going to work with all STL.
However if don't want to have function3 as a template, there is still a way. Unlike function pointer, the std::function (C++11 only, use boost::function for older compilers) template can be constructed from any functor (which includes plain function pointers). So given the above, you can write:
void function3(std::function<bool ()(char)> input_function) { ... input_function(something) ... }
and now you can still call:
function3(function2());
The point is that std::function has a template constructor that internally generates a template wrapper and stores a pointer to it's method, which is than callable without further templates.
Compiler don't use context of expression to deduce its template parameters. For compiler, function3(function2()); looks as
auto tmp = function2();
function3(tmp);
And it don't know what function2 template parameter is.
After your edit, I think what you want to do can be done simpler. See the following type:
struct Cmp {
bool const reverse;
Cmp(bool reverse) : reverse(reverse) {}
template <typename T> bool operator()(T a, T b) {
return reverse != (a < b);
}
};
Now, in your operator< you return an untyped Cmp instance depending on the order of your arguments, i.e. m_2 < m_1 would return Cmp(true) and m_1 < m_2 would return Cmp(false).
Since there is a templated operator() in place, the compiler will deduce the right function inside sort, not at your call to sort.
I am not sure if this help you and I am not an expert on this. I have been watching this post since yesterday and I want to participate in this.
The template cannot deduce it's type because the compiler does not know what type you are expecting to return. Following is a simple example which is similar to your function2().
template<typename T>
T foo() {
T t;
return t;
};
call this function
foo(); // no type specified. T cannot be deduced.
Is it possible to move the template declaration to the class level as follows:
template<typename T>
bool my_func_greater (const T& a, const T& b) {
return a > b;
}
template<typename T>
bool my_func_lesser (const T& a, const T& b) {
return b > a;
}
template <typename T>
class my_comparing {
public:
int value;
my_comparing(int value) : value(value) {}
bool (*operator<(const my_comparing& another) const)(const T&, const T&) {
if (this->value == 1 && another.value == 2) {
return my_func_greater<T>;
} else {
return my_func_greater<T>;
}
}
};
and declare m_1 and m_2 as below:
const my_comparing<int>& m_1 = my_comparing<int>(1);
const my_comparing<int>& m_2 = my_comparing<int>(2);
Now you can compare as follows:
if( m_1 < m_2 )
cout << "m_1 is less than m_2" << endl;
else
cout << "m_1 is greater than m_2" << endl;
I know this is simple and everyone knows this. As nobody posted this, I want to give a try.