std::shared_ptr<double[2]> constructor problems - c++11

The current C++ compilers fail to find a suitable overload for std::shared_ptr when using a C-array as a type.
I can make it a real std::array object and that works, but the library I'm linking against (fftw3) has already created the typedef and uses it in all of it's C-API calls.
#include <memory>
typedef double fftw_complex[2];
int main(int argc, char* argv[])
{
fftw_complex bob; //works fine
bob[0]=2; bob[1]=-1; //works fine
std::shared_ptr<fftw_complex> handle; //works fine
std::shared_ptr<double> other(new double[35]); //works fine
handle = std::shared_ptr<fftw_complex>(new fftw_complex[35]);//can't find constructor
return 0;
}
Up until a few months ago this worked fine with all compilers. With the update to gcc to version 7.3, 8.2, and 9 I now get an error when trying to compile the non-void constructor. I suspect it is because of the "improvements" to std::shared_ptr to automatically handle when T is an array type.
I get the error
complex_shared.cpp:12:61: error: no matching function for call to 'std::shared_ptr<double [2]>::shared_ptr(double (*)[2])'
12 | handle = std::shared_ptr<fftw_complex>(new fftw_complex[35]);
and the somewhat difficult to parse error message
note: candidate: 'template<class _Yp, class> std::shared_ptr<_Tp>::shared_ptr(_Yp*)'
139 | shared_ptr(_Yp* __p) : __shared_ptr<_Tp>(__p) { }
| ^~~~~~~~~~
/usr/local/Cellar/gcc/9.2.0/include/c++/9.2.0/bits/shared_ptr.h:139:2: note: template argument deduction/substitution failed:
/usr/local/Cellar/gcc/9.2.0/include/c++/9.2.0/bits/shared_ptr.h: In substitution of 'template<class _Tp> template<class ... _Args> using _Constructible = typename std::enable_if<std::is_constructible<std::__shared_ptr<_Tp>, _Args ...>::value>::type [with _Args = {double (*)[2]}; _Tp = double [2]]':
/usr/local/Cellar/gcc/9.2.0/include/c++/9.2.0/bits/shared_ptr.h:137:30: required from here
/usr/local/Cellar/gcc/9.2.0/include/c++/9.2.0/bits/shared_ptr.h:106:8: error: no type named 'type' in 'struct std::enable_if<false, void>'
106 | using _Constructible = typename enable_if<

it seems you have to let std::shared_ptr know that this is not a normal pointer but is indeed a pointer to an array
#include <memory>
typedef double fftw_complex[2];
int main(int argc, char* argv[])
{
fftw_complex bob;
bob[0]=2; bob[1]=-1;
std::shared_ptr<fftw_complex[]> handle;
std::shared_ptr<double> other(new double[35],[](double* p){ delete[] p;});
std::shared_ptr<double[]> nother(new double[35]); //std::shared_ptr will call delete[]
handle = std::shared_ptr<fftw_complex[]>(new fftw_complex[35], [](fftw_complex* p){ /* special delete logic*/;});
return 0;
}
to be clear, I have to use the fftw_malloc and fftw_free functions for this memory, so I will be providing my own deleter for the fftw_complex type. delete[] is incorrect for these library-provided data elements.

Related

Operating on thrust::complex types with thrust::transform

I'm trying to use thrust::transform to operate on vectors of type thrust:complex<float> without success. The following example blows up during compilation with several pages of errors.
#include <cuda.h>
#include <cuda_runtime.h>
#include <cufft.h>
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/transform.h>
#include <thrust/complex.h>
int main(int argc, char *argv[]) {
thrust::device_vector< thrust::complex<float> > d_vec1(4);
thrust::device_vector<float> d_vec2(4);
thrust::fill(d_vec1.begin(), d_vec1.end(), thrust::complex<float>(1,1));
thrust::transform(d_vec1.begin(), d_vec1.end(), d_vec2.begin(), thrust::abs< thrust::complex<float> >() );
}
I'm using CUDA 8.0 on Ubuntu Xenial and compiling with clang 3.8.0-2ubuntu4 using nvcc --std=c++11 main.cpp -o main.
Main errors appear to be:
main.cpp: In function ‘int main(int, char**)’:
main.cpp:17:105: error: no matching function for call to ‘abs()’
gin(), d_vec1.end(), d_vec2.begin(), thrust::abs< thrust::complex<float> >() );
and
/usr/local/cuda-8.0/bin/../targets/x86_64-linux/include/thrust/detail/complex/arithmetic.h:143:20: note: template argument deduction/substitution failed:
main.cpp:17:105: note: candidate expects 1 argument, 0 provided
gin(), d_vec1.end(), d_vec2.begin(), thrust::abs< thrust::complex<float> >() );
^
No problem working on real floats, but no such with complex ones. I'm thinking there's a type error that I'm missing, but I'm very much still on the steep part of the learning curve with Thrust & templates.
The error message is quite descriptive:
thrust::abs<thrust::complex<...>> is a function which expects exactly one parameter, see thrust/detail/complex/arithmetic.h#L143:
template <typename ValueType>
__host__ __device__
inline ValueType abs(const complex<ValueType>& z){
return hypot(z.real(),z.imag());
}
For your use case, you need to wrap that function by a functor:
struct complex_abs_functor
{
template <typename ValueType>
__host__ __device__
ValueType operator()(const thrust::complex<ValueType>& z)
{
return thrust::abs(z);
}
};
Finally, employ that functor here:
thrust::transform(d_vec1.begin(),
d_vec1.end(),
d_vec2.begin(),
complex_abs_functor());

#including <alsa/asoundlib.h> and <sys/time.h> results in multiple definition conflict

Here is the minimal C program to reproduce:
#include <alsa/asoundlib.h>
#include <sys/time.h>
int main( void )
{
}
This will compile with gcc -c -o timealsa.o timealsa.c, but if you include the -std=c99 switch, you get a redefinition error:
In file included from /usr/include/sys/time.h:28:0,
from timealsa.c:3:
/usr/include/bits/time.h:30:8: error: redefinition of ‘struct timeval’
struct timeval
^
In file included from /usr/include/alsa/asoundlib.h:49:0,
from timealsa.c:2:
/usr/include/alsa/global.h:138:8: note: originally defined here
struct timeval {
^
How can I resolve this conflict while still using -std=c99?
Since your question suggests you are using GLIBC's time.h there is a way to avoid this by telling it not to define timeval. Include asoundlib.h first then define _STRUCT_TIMEVAL. The one defined in asoundlib.h will be the one that gets used.
#include <alsa/asoundlib.h>
#ifndef _STRUCT_TIMEVAL
# define _STRUCT_TIMEVAL
#endif
#include <sys/time.h>
int main( void )
{
}
With C99 and later you can't have duplicate definitions of the same struct. The problem is that alsa/asoundlib.h includes alsa/global.h which contains this code:
/* for timeval and timespec */
#include <time.h>
...
#ifdef __GLIBC__
#if !defined(_POSIX_C_SOURCE) && !defined(_POSIX_SOURCE)
struct timeval {
time_t tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
#endif
#endif
So the Michael Petch's solution won't work - by the time you've included alsa/asoundlib.h it is already too late. The proper solution is to define _POSIX_C_SOURCE (_POSIX_SOURCE is obsolete). There's more information about these macros here and here.
For example you could try -D_POSIX_C_SOURCE=200809L. However, if you do that you'll get errors like this:
/usr/include/arm-linux-gnueabihf/sys/time.h:110:20: error: field ‘it_interval’ has incomplete type
struct timeval it_interval;
^
/usr/include/arm-linux-gnueabihf/sys/time.h:112:20: error: field ‘it_value’ has incomplete type
struct timeval it_value;
^
/usr/include/arm-linux-gnueabihf/sys/time.h:138:61: error: array type has incomplete element type
extern int utimes (const char *__file, const struct timeval __tvp[2])
^
This is all a big mess of old C code and macro madness. The only way I got it to work was to give up and use -std=gnu11.

g++ fails to look up static functions in a template class, is it a bug or standard defined?

When I try some C++11 code like following, it passed in all clang++ available to me that support C++11, but it failed to compile in g++-4.8, g++-4.9 and g++-5.0.
#include <type_traits>
#include <vector>
template <class C, class First, class Last>
struct HasInsertEnd {
template <class U>
static std::false_type Check(...);
template <class U>
static auto Check(U val)
-> decltype(val.insert(val.end(), std::declval<First>(),
std::declval<Last>()),
std::true_type{});
template <class U>
using Deduce = decltype(Check<U>(std::declval<U>()));
using type = typename Deduce<C>::type;
static constexpr bool value = type::value;
};
int main(int argc, char* argv[]) {
static_assert(!HasInsertEnd<int, int, int>::value, "...");
static_assert(HasInsertEnd<std::vector<int>, const int*, const int*>::value,
"...");
return 0;
}
g++ will report errors like:
‘Check’ was not declared in this scope
If I change the calling of Check in the Deduce to HasInsertEnd::Check, both g++ and clang++ will be happy.
I know little about dependent name lookup. The problem is, which behavior is standard?
This is a bug in GCC, and can be shown to be a bug in GCC even without deferring to the standard.
template <typename T>
struct f { typedef int type; };
template <typename T>
struct S {
template <typename U>
static f<U> f();
template <class U>
using u = typename decltype(f<U>())::type;
using t = u<T>;
};
S<int>::t main() { }
This is rejected the same way in GCC 4.7.4 and GCC 5, with "error: ‘f’ was not declared in this scope". That's just nonsense. Even if the static member function should somehow not be visible, there is still a global type by the same name that would be found instead. It gets even better, though: with that global type, you get:
test.cc: In substitution of ‘template<class T> template<class U> using u = typename decltype (f<U>())::type [with U = T; T = T]’:
test.cc:12:20: required from here
test.cc:10:36: error: ‘f’ was not declared in this scope
using u = typename decltype(f<U>())::type;
^
test.cc:10:36: note: suggested alternative:
test.cc:2:12: note: ‘f’
struct f { typedef int type; };
^
test.cc:15:13: error: ‘t’ in ‘struct S<int>’ does not name a type
S<int>::t main() { }
^
That's right, it's suggesting that f can be corrected by spelling it f.
I don't see any problem with your code, and if it isn't a known bug, I encourage you to report it. and it's been reported as a bug before.
Oddly, as noted in the comments, GCC 4.8.4 and GCC 4.9.2 do find a global f. However, if the global f is a type, then they still reject the program, with "error: missing template arguments" even though the template argument is provided, so it's still clearly a bug in GCC.

std::initializer_list with Multiple Types

I'm having trouble with std::initializer_list. I reduced it down to a simple example:
#include <initializer_list>
#include <cstdio>
class Test {
public:
template <typename type> Test(const std::initializer_list<type>& args) {}
};
int main(int argc, char* argv[]) {
Test({1,2});
getchar();
return 0;
}
When compiled using g++ test_initializer.cpp -std=c++0x, it compiles and runs well. However, if line 11 is changed to Test({1,2.0});, one gets:
ian#<host>:~/Desktop$ g++ test_initializer.cpp -std=c++0x
test_initializer.cpp: In function ‘int main(int, char**)’:
test_initializer.cpp:11:14: error: no matching function for call to ‘Test::Test(<brace-enclosed initializer list>)’
test_initializer.cpp:11:14: note: candidates are:
test_initializer.cpp:7:28: note: template<class type> Test::Test(const std::initializer_list<_Tp>&)
test_initializer.cpp:5:7: note: constexpr Test::Test(const Test&)
test_initializer.cpp:5:7: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘const Test&’
test_initializer.cpp:5:7: note: constexpr Test::Test(Test&&)
test_initializer.cpp:5:7: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘Test&&’
I suspect this happens because the compiler can't figure out what type to make the initializer list. Is there a way to fix the example so that it works with different types (and still uses initializer lists)?
An std::initializer_list takes only one type. If you need different types, you can use variadic templates:
template<typename... Args>
Test(Args&&... args);
/* ... */
int main()
{
Test(1, 2.0);
}
Would a std::tuple<int.double> work for the OP? If the code will always have a int followed by a double, then the OP could get strict type-checking for all arguments, which the variable arguments solution does not allow. The std::tuple<>, however, would not work for any number or order of values, so may not be appropriate for all use cases.
Let the initializer_list hold the most arbitrary pointers, void*, and do your own casting from there. Here is an example.
#include <initializer_list>
#include <iostream>
using std::initializer_list;
using std::cout;
using std::endl;
class Person {
private:
string _name;
int _age;
public:
Person(initializer_list<void*> init_list) {
auto it = init_list.begin();
_name = *((string*)(*it));
it++;
_age = *((int*)(*it));
}
void print() {
cout << "name: " << _name << ". age: " << _age << endl;
}
};
int main(void) {
string name{"Vanderbutenburg};
int age{23};
Person p{&name,&age};
p.print(); // "name: Vanderbutenburg. age: 23"
return 0;
}

VC++ WINAPI Form: Identifier Not Found (C3861 Error)

I'm working on a port from some old Delphi code to VC++ 2013, and I'm encountering an error that I feel should be an easy fix but cannot for the life of me figure out...
The problem is this: I have a number of common utility functions in a local file Utils.h that I am deploying as part of a windows form. Most (90%) of the functions in this header work as normal. GetMsg(...), however, throws a C3861 Identifier not found error...
Utils.h (snippet): GetMsg declared at bottom
#pragma once
/*------------------------------------------------------------------------*
Includes:
*------------------------------------------------------------------------*/
using namespace std;
/*------------------------------------------------------------------------*
Constants:
*------------------------------------------------------------------------*/
#define GET_MSG_TIMEOUT 2
/*------------------------------------------------------------------------*
Typedefs, Structs, Enums:
*------------------------------------------------------------------------*/
typedef union
{
unsigned long ui32;
unsigned char ui8[4];
} UI32_UI8;
typedef union
{
unsigned short ui16;
unsigned char ui8[2];
} UI16_UI8;
typedef union
{
float f;
unsigned char ui8[4];
} F_UI8;
typedef struct
{
string sName;
string sVersion;
string sCompany;
string sCopyright;
} PRODUCT_INFORMATION;
/*------------------------------------------------------------------------*
Prototypes:
*------------------------------------------------------------------------*/
unsigned short SwapShort(unsigned short aShort);
float SwapFloat(float aFloat);
unsigned long SwapLong(unsigned long aLong);
unsigned int ReadLine(unsigned char *msgBuf, SerialPort^ Hdl, bool ReturnLF);
void __stdcall FillTheBuffer(char *buf, String sss, int length);
string __stdcall FillTheString(string sss, int length);
unsigned int __stdcall GetMsg(SerialPort^ Hdl, unsigned char *msgBuf);
GetMsg Definition in Utils.cpp:
//---------------------------------------------------------
unsigned int __stdcall GetMsg(SerialPort^ Hdl, unsigned char *msgBuf)
{
...
}
And, finally, GetMsg usage in form file:
#include "Utils.h"
...
void MainForm::UploadButton_Click
(System::Object^ object, System::EventArgs^ e)
{
...
SwapShort(1); //Works fine, also declared in Utils.h
GetMsg(spCom, inBuf); //C3861 ERROR
...
}
Where spCom is a (SerialPort^) contained, configured, and opened within the windows form. inBuf is a simple array of characters (char*) to buffer the input. I've tried renaming the function, thinking that there may have been an unintentional conflict / overload in other files, to no avail.
Any advice? Thanks, in advance
Solved the problem -- As it turns out I needed to be more explicit in my function definitions. Changing the declaration to read
GetMsg(System::IO::Ports::SerialPort^ Hdl, unsigned char *msgBuf)
eliminated the C3861 error. It would seem that the lack of a specific namespace on the declaration passed Intellisense but confused the compiler, rendering it unable to determine which prototype to use with the function call.

Resources