pointer parameter passed by reference in a function c++ - c++

I have a class template which has a member variable std::vector<T> buffer and a member function setData, among others.
template <class T>
void ArrayT<T>::setData(const std::vector<T> * & data_ptr) {
buffer.assign(data_ptr->begin(), data_ptr->end());
}
I want setData to perform a deep copy of the data passed as its argument. As you can see, the argument is of type * &, which if I understand well is a pointer parameter passed by reference.
When I write:
vector<float> vec(3, 1.0);
vector<float>* vec2 = &vec;
A obj();
obj.setData(vec2);
I get an error:
E0434 a reference of type "const std::vector<float, std::allocator<float>> *&" (not const-qualified) cannot be initialized with a value of type "std::vector<float, std::allocator<float>> *"
Could someone please explain how to fix this?

The input parameter of setData() is a reference to a non-const pointer to a const std::vector. But the std::vector object you are pointing at is not const.
There is no reason to use a pointer at all in this situation. Change setData() to take the std::vector by const reference instead:
template <class T>
void ArrayT<T>::setData(const std::vector<T> &data)
{
buffer.assign(data.begin(), data.end());
// or simply: buffer = data;
}
vector<float> vec(3, 1.0);
Array<float> obj;
obj.setData(vec);
That being said, if you want to keep the pointer, you need to drop the const:
template <class T>
void ArrayT<T>::setData(std::vector<T> * data_ptr)
{
buffer.assign(data_ptr->begin(), data_ptr->end());
// or simply: buffer = *data_ptr;
}
Or at least move the const after the * to make the pointer itself const rather than the object it is pointing at:
template <class T>
void ArrayT<T>::setData(std::vector<T> * const data_ptr)
{
buffer.assign(data_ptr->begin(), data_ptr->end());
// or simply: buffer = *data_ptr;
}
Either way, notice I removed the reference. There is no good reason to pass a pointer by reference when you are not modifying what the pointer is pointing at. Pass the pointer by value instead.

Related

How to pass a reference to a template typename argument

Is there a way to pass a reference as an argument to a template typename argument? I mean so instead of passing an int, for example, to pass a reference to an int.
template <typename T>
struct Foo
{
Foo(T arg) : ptr(arg) {}
T ptr;
};
int main()
{
int* a = new int(6);
Foo<decltype(a)> foo1(a); // ptr is a copy of a pointer
Foo<decltype(&a)> foo1(&a); // ptr seems to be a pointer to a pointer
}
I know I can make the 'ptr' member be a reference to a pointer by making it T& in the class, but I was wondering if this can be done from argument that's passed to the template argument.
You're looking for Foo<decltype(a) &> foo1(a).
A more obscure alternative (which works in this specific case) is Foo<decltype((a))> foo1(a).
As an alternative to the previous answer, you can use std::reference_wrapper
std::reference_wrapper is a class template that wraps a reference in a
copyable, assignable object. It is frequently used as a mechanism to
store references inside standard containers (like std::vector) which
cannot normally hold references.
#include <functional>
template <typename T>
struct Foo
{
Foo(T arg) : ptr(arg)
{
}
T ptr;
};
int main()
{
int* a = new int(6);
Foo<std::reference_wrapper<int*>> foo1(std::ref(a));
foo1.ptr[0] = 1; // ok
// This also works
int* b = new int(6);
Foo<std::reference_wrapper<decltype(b)>> foo2(std::ref(b));
// and this too
foo1 = foo2;
// Or, if you use c++17, even this
Foo foo3(std::ref(b));
}

passing std::function as parameter with const void *

I have the following function declaration:
void get_data(struct myStruct* const value, const void * const data);
I have another function that I want to add a std::function as a parameter:
// I think the std::function definition is where my problem is
template<typename MyType>
void process(bool test, std::function<void(MyType* const, const void* const)>& callb) { ... }
However I can't quite figure out how to call it, or rather if my definition above is correct:
bool test1 = true;
process<myStruct>(test1, get_data);
Compiler Error:
error: prototype for ‘void process(bool, std::function<void(MyType* const, const void* const)>&)’ does not match any in class ‘MyClass’
void process(bool test,
error: candidate is: template<class MyType> void process(bool, std::function<void(MyType*, const void*)>&)
void process(bool test,
... goes on
Any ideas?
You basically just have to remove the reference from the function object:
void process(bool test, std::function<void(MyType* const, const void* const)> callb);
While a reference to a std::function object cannot be related to/converted from the underlying function pointer type, the non-referenced object can be implicitely converted to the function pointer type thanks to its constructor.
Edit: Passing std::function as const reference gives no performance benefit, but may actually include some penalty in some corner cases, see Should I pass an std::function by const-reference?
When passing get_value to callb, the compiler has to construct a temporary std::function object for callb. But callb is declared as a non-const reference, which cannot be bound to a temporary object. So make callb be a const reference instead, which can be bound to a temporary:
template<typename MyType>
void process(bool test, const std::function<void(MyType* const, const void* const)>& callb) { ... }
Live Demo

Passing by reference to a template function

I'm having a function of finding max and I want to send static array via reference, Why isn't this possible?
template <class T>
T findMax(const T &arr, int size){...}
int main{
int arr[] = {1,2,3,4,5};
findMax(arr, 5); // I cannot send it this way, why?
return 0;
}
Use correct syntax. Change signature to:
template <class T, size_t size>
T findMax(const T (&arr)[size]){...}
Or you can use std::array argument for findMax() function.
Live Example
Why isn't this possible?
const T &arr: Here arr is a reference of type T and not the reference to array of type T as you might think. So you need [..] after arr. But then it will decay to a pointer.
Here you can change the binding with () and use const T (&arr)[SIZE].
For more, you can try to explore the difference between const T &arr[N] v/s const T (&arr)[N].

template deduction: const reference and const pointer

template <typename T>
void f(T t)
{}
int x = 1;
const int & rx = x;
const int * px = &x;
f(rx); // t is int
f(px); // t is const int *, instead of int *, WHY???
I'm confused now. According to Effective Modern c++,
It’s important to recognize that const is ignored only for by-value
parameters. As we’ve seen, for parameters that are references-to- or
pointers-to-const, the constness of expr is preserved during type
deduction.
I think it means
template <typename T>
void f(T * t)
{}
f(px); // t is const int *
template <typename T>
void f(T & t)
{}
f(cx); // t is const int &
template <typename T>
void f(T t)
{}
f(value); // const or volatile of value will be ignored when the type of the parameter t is deduced
So I think when f(px) above, t should be int *, but in fact it is const int *.
Why the const of reference is ignored but the const of pointer isn't?
Or, why isn't rx const int &?
So I think when f(px) above, px should be int *, but in fact it is const int *.
The point is the type of parameter, behaviors change for passed-by-value and passed-by-reference/pointer.
When passed-by-value, the constness of the argument itself is ignored. For a pointer parameter, the constness of pointer is ignored (const pointer -> pointer), but the constness of pointee is still preserved (pointer to const -> pointer to const).
It does make sense because when pass a pointer, the pointer itself is copied, but the pointee is the same, they're both pointing to the same thing, so constness of pointee is preserved; from the point of callers, they won't want the object to be modified, they might use it later. While pass a reference (reference doesn't matter in fact here), you'll get a brand new value copied, which has nothing to do with the original one, then constness is ignored.
As the following explanations in the book, when const pointer to const (a const char* const) passed,
template<typename T>
void f(T param); // param is still passed by value
const char* const ptr = // ptr is const pointer to const object
"Fun with pointers";
f(ptr); // pass arg of type const char * const
The type deduced for param will be const char*.
Only top-level const/volatile qualifiers are ignored. All others are inherent qualities of your type. In other words, you're copying a pointer - it means the function operates on a copy and any modifications to it (like assigning another variable's address) do not modify the original pointer. But if you pass a pointer to const int, having the function modify the integer is very much counter-intuitive.
template <typename T>
void f(T t)
{
t = &another_variable; // ok
}
f(px);
and
void f(T t)
{
*t = 42; // not ok!
}
f(px); // secretly modifying `x` through a pointer to const...
Reference: this answer for pointer to const vs. const pointer differences

C++ passing a const pointer by const reference

Hmm a strange one in VC2012 I can't seem to work out the syntax for passing a const pointer by const reference into a function of a templated class whose template argument is a non const pointer ie:
template<typename T>
struct Foo
{
void Add( const T& Bar ) { printf(Bar); }
};
void main()
{
Foo<char*> foo;
const char* name = "FooBar";
foo.Add(name); // Causes error
}
So I've simplified my problem here but basically I want the argument to 'Add' to have a const T ie const char*. I've tried:
void Add( const (const T)& Bar );
typedef const T ConstT;
void Add( const (ConstT)& Bar );
void Add( const typename std::add_const<T>::type& Bar );
None of which work. The exact error I'm getting is:
error C2664: 'Foo<T>::Add' : cannot convert parameter 1 from 'const char *' to 'char *const &'
with
[
T=char *
]
Conversion loses qualifiers
which I can see is correct but how do I solve it without const casting 'name' to be non const.
There is a strong difference between a pointer to a constant object (T const*, or const T*) and a constant pointer to a non-constant object (T * const). In your case the signature of the member Add is:
void Foo<char *>::Add(char * const& ); // reference to a constant pointer to a
// non-constant char
I usually recommend that people drop the use of const on the left hand side exactly for this reason, as beginners usually confuse typedefs (or deduced types) with type substitution and when they read:
const T& [T == char*]
They misinterpret
const char*&
If the const is placed in the right place:
T const &
Things are simpler for beginners, as plain mental substitution works:
char * const &
A different problem than what you are asking, but maybe what you think you want, is:
Given a type T have a function that takes a U that is const T if T is not a pointer type, or X const * if T is a pointer to X
template <typename T>
struct add_const_here_or_there {
typedef T const type;
};
template <typename T>
struct add_const_here_or_there<T*> {
typedef T const * type;
};
Then you can use this in your signature:
template <typename T>
void Foo<T>::Add( const typename add_const_here_or_there<T>::type & arg ) {
...
Note that I am adding two const in the signature, so in your case char* will map to char const * const &, as it seems that you want to pass a const& to something and you also want the pointed type to be const.
You might have wondered as of the name for the metafunction: *add_const_here_or_there*, it is like that for a reason: there is no simple way of describing what you are trying to do, which is usually a code smell. But here you have your solution.
It looks like your issue here as that as soon as you have a pointer type mapped to a template type, you can no longer add const-ness to the pointed-to type, only to the pointer itself. What it looks like you're trying to do is automatically add constness to the parameter of your function (so if T is char* the function should accept const char* const& rather than char* const& as you've written). The only way to do that is with another template to add constness to the pointee for pointer types, as follows. I took the liberty of including missing headers and correcting the signature of main:
#include <cstdio>
template<typename T>
struct add_const_to_pointee
{
typedef T type;
};
template <typename T>
struct add_const_to_pointee<T*>
{
typedef const T* type;
};
template<typename T>
struct Foo
{
void Add( typename add_const_to_pointee<T>::type const & Bar ) { printf(Bar); }
};
int main()
{
Foo<char*> foo;
const char* name = "FooBar";
foo.Add(name); // Causes error
}
As mentioned in another another however, this issue just goes away if you use std::string instead of C-style strings.
You need to change the template argument to your Foo object to Foo<const char*>. Because if T=char*, then const T=char*const, not const char*. Trying to coerce it to work is not a good idea and would probably result in undefined behavior.
Use:
Foo<const char*> foo;
const char* name = "FooBar";
foo.Add(name);
And write int main() instead of void main()
If passing const char* instead of char* to Foo is not an option you can finesse the correct type with std::remove_pointer. This will remove the pointer modifier and allow you to provide a more explicit type.
#include <type_traits>
template<typename T>
struct Foo
{
void Add(typename std::remove_pointer<T>::type const*& Bar ) { printf(Bar); }
};
To prevent the pointer value from being modified you can declare the reference as const as well.
void Add(typename std::remove_pointer<T>::type const* const& Bar )
{ Bar = "name"; } // <- fails
If you need to reduce the type from say a pointer to pointer you can use std::decay along with std::remove_pointer
void Add(typename std::remove_pointer<typename std::decay<T>::type>::type const*& Bar)
{
printf(Bar);
}
This really depends on what your requirements for T are. I suggest assuming only the base type (e.g. char) is passed as T and building reference and pointer types from that.