Clang issue: Detecting constexpr function pointer with SFINAE - c++11

Based on the answer in Detecting constexpr with SFINAE I'm trying to use SFINAE to check if a 'constexpr' is present in my class.
The problem is that the constexpr is a function pointer:
#include <type_traits>
#include <iostream>
typedef int (*ptr_t)();
int bar() { return 9; }
struct Foo {
static constexpr ptr_t ptr = &bar;
};
namespace detail {
template <ptr_t>
struct sfinae_true : std::true_type {};
template <class T>
sfinae_true<T::ptr> check(int);
// Commented out to see why clang was not evaluating to true. This should only be
// a comment when debugging!
// template <class>
// std::false_type check(...);
} // detail::
template <class T>
struct has_constexpr_f : decltype(detail::check<T>(0)) {};
int main(int argc, char *argv[]) {
std::cout << has_constexpr_f<Foo>::value << std::endl;
return 0;
}
It seems to work fine using gcc, but clang complains:
test.cxx:23:39: error: no matching function for call to 'check'
struct has_constexpr_f : decltype(detail::check<T>(0)) {};
^~~~~~~~~~~~~~~~
test.cxx:26:22: note: in instantiation of template class 'has_constexpr_f<Foo>' requested here
std::cout << has_constexpr_f<Foo>::value << std::endl;
^
test.cxx:16:25: note: candidate template ignored: substitution failure [with T = Foo]: non-type template argument for template parameter of pointer type 'ptr_t' (aka 'int (*)()') must have its address taken
sfinae_true<T::ptr> check(int);
~ ^
1 error generated.
Q1: Can anyone suggest a way of doing this which works both for Clang and GCC?
Q2: Is this a bug in gcc, clang or is this left undefined in the c++ standard?

That's not a bug in clang, but an unfortunate restriction of arguments for non-type template parameters of pointer type (see pointer as non-type template argument). Essentially, you can only use arguments of the form &something: [temp.arg.nontype]/1 (from n3797)
[if the template-parameter is a pointer, its argument can be] a constant expression (5.19) that designates the address of a
complete object with static storage duration and external or
internal linkage or a function with external or internal linkage,
including function templates and function template-ids but excluding
non-static class members, expressed (ignoring parentheses) as &
id-expression, where the id-expression is the name of an object or
function, except that the & may be omitted if the name refers to a
function or array and shall be omitted if the corresponding
template-parameter is a reference; or [..]
[emphasis mine]
You can however, use a function pointer in a constant expression that has a non-pointer type, for example a boolean expression such as
T::ptr != nullptr
This works under clang++3.5 and g++4.8.2:
#include <type_traits>
#include <iostream>
typedef int (*ptr_t)();
int bar() { return 9; }
struct Foo0 {
static constexpr ptr_t ptr = &bar;
};
struct Foo1 {
static const ptr_t ptr;
};
ptr_t const Foo1::ptr = &bar;
struct Foo2 {
static const ptr_t ptr;
};
//ptr_t const Foo2::ptr = nullptr;
namespace detail
{
template <bool>
struct sfinae_true : std::true_type {};
template <class T>
sfinae_true<(T::ptr != nullptr)> check(int);
// the result of the comparison does not care
template <class>
std::false_type check(...);
} // detail::
template <class T>
struct has_constexpr_f : decltype(detail::check<T>(0)) {};
int main(int argc, char *argv[]) {
std::cout << std::boolalpha << has_constexpr_f<Foo0>::value << std::endl;
std::cout << std::boolalpha << has_constexpr_f<Foo1>::value << std::endl;
std::cout << std::boolalpha << has_constexpr_f<Foo2>::value << std::endl;
return 0;
}
Note there's a difference between clang++ and g++ for the second output (Foo1): g++ says true, clang++ says false.

Related

Add a vector<string> field to a cMessage

I'm building a custom cMessage that includes vectors as some fields. I have no issue with int or double vectors, but with string vectors, I get an error. Below is a sample message definition to reproduce the issue.
cplusplus {{
#include <vector>
typedef std::vector<int> IntVector;
typedef std::vector<string> StrVector;
}};
class IntVector { #existingClass; };
class StrVector { #existingClass; };
message sampleMessage extends cMessage
{
IntVector SampleIntVector;
StrVector SampleStrVector;
}
In my code, I have the below block
sampleMessage *msg = new sampleMessage();
vector<int> intVect = {1,2};
vector<string> stringVect;
string inputString = "dummy string";
stringVect.push_back(inputString);
msg->setSampleIntVector(intVect);
msg->setSampleStrVector(stringVect);
Using OMNeT++ version 6.0 pre10, at the 7th line, I get the error below suggesting the cMessage is expecting a vector<char *>
error: no viable conversion from 'vector<std::string>' to 'const vector<char *>'
I also tried on OMNeT++ version 5.6.2 and got a different error message. For clarity, the file testModel_m.cc is generated by OMNeT++.
testModel_m.cc:170:13: error: use of overloaded operator '<<' is ambiguous (with operand types 'std::ostream' (aka 'basic_ostream<char>') and 'const std::__cxx11::basic_string<char>')
out << *it;
~~~ ^ ~~~
testModel_m.cc:2040:45: note: in instantiation of function template specialization 'operator<<<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char> > >' requested here
case 1: {std::stringstream out; out << pp->getSampleStrVector(); return out.str();}
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h:6416:5: note: candidate function [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
operator<<(basic_ostream<_CharT, _Traits>& __os,
^
testModel_m.cc:158:22: note: candidate function [with T = std::__cxx11::basic_string<char>]
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
If I change the vector to char *, it works, but for my use case, I would need a vector of string since I search for values in a vector and with char *, that doesn't work quite well.
Is there a way to have a vector<string> field as part of the custom cMessage?
The workaround for the error use of overloaded operator '<<' is ambiguous is adding own definition of operator<< inside cplusplus {{ }} block, for example:
cplusplus {{
#include <vector>
typedef std::vector<int> IntVector;
typedef std::vector<std::string> StrVector;
std::ostream& operator<<(std::ostream &os, const StrVector& vec) {
std::stringstream out;
for (auto i : vec) {
out << i << ", ";
}
return os << out.str();
};
}};
class IntVector { #existingClass; };
class StrVector { #existingClass; };
message sampleMessage {
IntVector SampleIntVector;
StrVector SampleStrVector;
}

CRTP traits only working with templated derived class

I have seen an idiom for using Derived type traits in the base class of a CRTP pattern that looks like this:
template<typename Derived>
struct traits;
template<typename Derived>
struct Base {
using size_type = typename traits<Derived>::size_type;
};
template <typename T>
struct Derived1 : Base<Derived1<T>>{
using size_type = size_t;
void print(){ std::cout << "Derived1" << std::endl; }
};
template <typename T>
struct traits<Derived1<T>> {
using size_type = size_t;
};
int main()
{
using T = float;
Derived1<T> d1;
d1.print();
}
My understanding is that the purpose of the idiom is to delay the instantiation of the Base class's size_type. What I am confused by is the fact that this pattern only seems to work if the derived class is itself templated. For instance, if we change the code to:
template<typename Derived>
struct traits;
template<typename Derived>
struct Base {
using size_type = typename traits<Derived>::size_type;
};
struct Derived1 : Base<Derived1>{
using size_type = size_t;
void print(){ std::cout << "Derived1" << std::endl; }
};
template <>
struct traits<Derived1> {
using size_type = size_t;
};
int main()
{
Derived1 d1;
d1.print();
}
then we get the error
prog.cc: In instantiation of 'struct Base<Derived1>':
prog.cc:21:19: required from here
prog.cc:18:58: error: invalid use of incomplete type 'struct traits<Derived1>'
using size_type = typename traits<Derived>::size_type;
^
prog.cc:14:8: note: declaration of 'struct traits<Derived1>'
struct traits;
^~~~~~
prog.cc: In function 'int main()':
prog.cc:33:9: error: 'Derived1' is not a template
Derived1<float> d1;
Could somebody give me an explanation indicating why the templated derived class compiles, but the untemplated class does not?
The issue you're seeing has nothing to do with CRTP.
Here's what the standard mentions.
If a class template has been declared, but not defined, at the point of instantiation (13.7.4.1),
the instantiation yields an incomplete class type (6.7). [Example:
template<class T> class X; X<char> ch; // error: incomplete type
X<char>
Your traits has only been declared at the point of instantiation of Base<Derived>, hence as per the standard(see above extraction from the standard), struct traits<Derived> yields an incomplete type.
You should reorder the code so that it sees the traits<Derived> specialization when Base<Derived> gets instantiated.
The compilation error you are seeing has nothing to do with CRTP, it's just a bit of a mish-mash of dependencies.
In the code without the templation, your "Base" struct needs the definition of the specialized "traits" struct but it only appears afterwards, so it tries to use the incomplete type it saw in the declaration above.
To get the code to work you need to have the "traits" specialization before the Base declaration, which requires you to also add a declaration of Derived 1, here is a compiling code:
class Derived1;
template<typename Derived>
struct traits;
template <>
struct traits<Derived1> {
using size_type = size_t;
};
template<typename Derived>
struct Base {
using size_type = typename traits<Derived>::size_type;
};
struct Derived1 : Base<Derived1>{
using size_type = size_t;
void print(){ std::cout << "Derived1" << std::endl; }
};
int main()
{
Derived1 d1;
d1.print();
}

Identify pointers in a tuple c++11

I need to convert a tuple to a byte array. This is the code I use to convert to byte array:
template< typename T > std::array< byte, sizeof(T) > get_bytes( const T& multiKeys )
{
std::array< byte, sizeof(T) > byteArr ;
const byte* start = reinterpret_cast< const byte* >(std::addressof(multiKeys) ) ;
const byte* end = start + sizeof(T);
std::copy(start, end, std::begin(byteArr));
return byteArr;
}
Here is how I call it:
void foo(T... keyTypes){
keys = std::tuple<T... >(keyTypes...);
const auto bytes = get_bytes(keys);
}
I need to augment this code such that when a pointer is a part of the tuple, I dereference it to it's value and then pass the new tuple, without any pointers, to the get_bytes() function. How do I detect the presence of a pointer in the tuple? I can then iterate through the tuple and dereference it with:
std::cout << *std::get<2>(keys) << std::endl;
Add a trivial overload: T get_bytes(T const* t) { return getBytes(*t); }.
That would be easy with C++14 :
#include <iostream>
#include <tuple>
#include <utility>
template <class T> decltype(auto) get_dereferenced_value(T &&value) {
return std::forward<T>(value);
}
template <class T> decltype(auto) get_dereferenced_value(T *value) {
return *value;
}
template <class Tuple, class Indexes> struct get_dereferenced_tuple_impl;
template <class... Args, size_t... Index>
struct get_dereferenced_tuple_impl<std::tuple<Args...>,
std::integer_sequence<size_t, Index...>> {
decltype(auto) operator()(std::tuple<Args...> const &originalTuple) {
return std::make_tuple(
get_dereferenced_value(std::get<Index>(originalTuple))...);
}
};
template <class Tuple>
decltype(auto) get_dereferenced_tuple(Tuple const &tupleValue) {
return get_dereferenced_tuple_impl<
Tuple,
std::make_integer_sequence<size_t, std::tuple_size<Tuple>::value>>{}(
tupleValue);
}
int main() {
char c = 'i';
std::tuple<char, char *> t{'h', &c};
auto t2 = get_dereferenced_tuple(t);
std::cout << std::get<0>(t2) << std::get<1>(t2) << "\n";
return 0;
}
If you cannot use C++14, then you would have to write more verbose decltype expressions, as well as include an implementation of std::(make_)integer_sequence.
This has a drawback though : copies will be made before copying the bytes. A tuple of references is not a good idea. The most performant version would be a get_bytes able to serialize the entire mixed tuple directly.

GCC produce "could not convert" error when using aggregate initialization

I'm trying to make C-string size calculation at compile time, using code like this:
#include <stdio.h>
#include <stdint.h>
class StringRef
{
public:
template<int N>
constexpr StringRef(const char (&str)[N])
: m_ptr(str), m_size(uint32_t(N-1)) {}
constexpr const char *constData() const
{ return m_ptr; }
private:
const char *m_ptr;
uint32_t m_size;
};
struct S
{
StringRef str;
};
constexpr static const struct S list[] =
{
"str",
};
int main()
{
printf("%s\n", list[0].str.constData());
return 0;
}
In clang-3.7 everything is fine, but in GCC 4.9.3-5.3 I get:
error: could not convert '(const char*)"str"' from 'const char*' to
'StringRef'
It can be fixed by adding explicit braces:
constexpr static const struct S list[] =
{{
{ "str" },
}};
But code became ugly and, still, clang somehow understand it correctly.
How can I make gcc understand array initialization without explicit braces?

protected members in a template deduction context: compilation error, substitution fails, or succeeds?

g++ 5.2.1 fails to compile when it encounters a private method's address in a template deduction context whereas clang 3.5 only discards the specialization.
g++ 5.2.1 can access protected members of parents/friends in a class template parameter list when clang 3.5 sometimes fail to do so.
Which are wrong in which cases?
More precisely:
Should the compiler cause a hard error when trying to access a non accessible protected/private member in a template deduction context? Am I doing something wrong in my first example?
If not, should the compiler discard a specialization when trying to access (in a template deduction context) a protected member owned by:
a base class of this specific specialization
a class which declared this specific instantiation as a friend
a friend class which declared any instantiation of this template as a friend
The first question seems to have already been answered here (and the answer seems to be "no, the code isn't ill-formed and the compiler should simply discard this specialization"). However, since it's a prerequisite to the second question (and g++ 5.2.1 doesn't seem to agree), I want to be absolutely sure that it's g++ 5.2.1 which is wrong, not me.
Longer version with examples
I would like to make traits able to detect whether some functions/methods are implemented, even if they are protected members of some class (if you find this odd, I'll explain why I want to do this at the end of this question so that you can tell me I'm completely wrong, should learn how to design my classes, and maybe suggest me a cleaner way to do so).
My problem is that each of my attempts fail on either clang or g++ (oddly enough, not both at the same time): Sometimes it compiles but don't provide the expected result, sometimes it doesn't compile at all.
Even though it seems it isn't practical, I at least want to know when the compilers are faulty, and when I'm writing ill-formed code. Hence this question.
I use the C++11 dialect, and my clang version is actually the compiler provided with XCode 5 i.e. Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn).
To better illustrate what my problem is, here is a minimal exemple where clang compiles but g++ 5.2.1 doesn't:
#include <iostream>
#include <type_traits>
#include <utility>
struct PrivateFoo {
private:
void foo() {}
};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
template<class C, class = void>
struct has_foo : std::false_type {};
template<class C>
struct has_foo<C, void_t<check_signature<void(C::*)(), &C::foo>>> :
std::true_type {};
int main() {
std::cout << std::boolalpha;
std::cout << "PrivateFoo has foo: " << has_foo<PrivateFoo>::value << '\n';
return 0;
}
output with clang 3.5:
PrivateFoo has foo: false
g++ 5.2.1 errors:
access_traits.cpp : [in instantiation of] ‘struct has_foo<PrivateFoo>’ :
access_traits.cpp:37:61: required from here
access_traits.cpp:7:8: [error]: ‘void PrivateFoo::foo()’ is private
void foo() {}
^
access_traits.cpp:32:56: [error]: [in context]
struct has_foo<C, void_t<check_signature<void(C::*)(), &C::foo>>> :
^
access_traits.cpp:7:8: [error]: ‘void PrivateFoo::foo()’ is private
void foo() {}
^
access_traits.cpp:32:56: [error]: [in context]
struct has_foo<C, void_t<check_signature<void(C::*)(), &C::foo>>> :
^
access_traits.cpp: [in function] ‘int main()’:
access_traits.cpp:7:8: erreur: ‘void PrivateFoo::foo()’ is private
void foo() {}
^
access_traits.cpp:37:42: [error]: [in context]
std::cout << "PrivateFoo has foo: " << has_foo<PrivateFoo>::value << '\n';
(text in brackets is translated, it was originally in my native language)
Here is an example where both compile but disagree on whether foo is accessible or not:
#include <iostream>
#include <type_traits>
#include <utility>
struct ProtectedFoo {
protected:
void foo() {}
};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
namespace detail {
template<class C, class = void>
struct has_foo_helper : std::false_type {};
template<class C>
struct has_foo_helper<C, void_t<decltype(std::declval<C>().foo())>> :
std::true_type {};
}
template<class C>
struct has_public_or_protected_foo : protected C {
template<class, class>
friend class detail::has_foo_helper;
static constexpr bool value =
detail::has_foo_helper<has_public_or_protected_foo<C>>::value;
};
int main() {
std::cout << std::boolalpha;
std::cout << "ProtectedFoo has foo: ";
std::cout << has_public_or_protected_foo<ProtectedFoo>::value << '\n';
return 0;
}
output with clang 3.5:
ProtectedFoo has foo: false
output with g++ 5.2.1:
ProtectedFoo has foo: true
and finally here is an example where both compile and agree that they should be able to access foo:
#include <iostream>
#include <type_traits>
#include <utility>
struct ProtectedFoo {
protected:
void foo() {}
};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
namespace detail {
template<class C, class D, class = void>
struct has_foo_helper : std::false_type {};
template<class C, class D>
struct has_foo_helper<C, D, void_t<check_signature<void(C::*)(), &D::foo>>> :
std::true_type {};
}
template<class C>
struct has_public_or_protected_foo : protected C {
template<class, class, class>
friend class detail::has_foo_helper;
static constexpr bool value =
detail::has_foo_helper<C, has_public_or_protected_foo<C>>::value;
};
int main() {
std::cout << std::boolalpha;
std::cout << "ProtectedFoo has foo: ";
std::cout << has_public_or_protected_foo<ProtectedFoo>::value << '\n';
return 0;
}
output with clang 3.5:
ProtectedFoo has foo: true
output with g++ 5.2.1:
ProtectedFoo has foo: true
Also here is a more complete example which summarizes it all:
#include <iostream>
#include <type_traits>
#include <utility>
/* test classes */
struct PublicFoo {
void foo() {}
};
struct ProtectedFoo {
protected:
void foo() {}
};
struct PrivateFoo {
private:
void foo() {}
};
struct NoFoo {};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
namespace detail {
template<class C, class D, class = void>
struct has_foo_helper : std::false_type {};
template<class C, class D>
struct has_foo_helper<C, D, void_t<check_signature<void(C::*)(), &D::foo>>> :
std::true_type {};
template<class C, class = void>
struct may_call_foo_helper : std::false_type {};
template<class C>
struct may_call_foo_helper<C, void_t<decltype(std::declval<C>().foo())>> :
std::true_type {};
}
template<class C>
struct has_foo : detail::has_foo_helper<C, C> {};
template<class C>
struct may_call_foo : detail::may_call_foo_helper<C> {};
template<class C>
struct has_protected_foo : protected C {
template<class, class, class>
friend class detail::has_foo_helper;
static constexpr bool value =
detail::has_foo_helper<C, has_protected_foo<C>>::value;
};
template<class C>
struct may_call_protected_foo : protected C {
template<class, class>
friend class detail::may_call_foo_helper;
static constexpr bool value =
detail::may_call_foo_helper<may_call_protected_foo<C>>::value;
};
/* test */
template<class T>
void print_info(const char* classname) {
std::cout << classname << "...\n";
// comment this if you want to compile with g++
//*
std::cout << "has a public method \"void foo()\": ";
std::cout << has_foo<T>::value << '\n';
std::cout << "has a public or protected method \"void foo()\": ";
std::cout << has_protected_foo<T>::value << '\n';
//*/
std::cout << "has a public method \"foo\" callable without any arguments: ";
std::cout << may_call_foo<T>::value << '\n';
std::cout << "has a public or protected method \"foo\" callable without any "
"arguments: ";
std::cout << may_call_protected_foo<T>::value << '\n';
std::cout << '\n';
}
int main() {
std::cout << std::boolalpha;
// both g++ 5.2.1 and clang 3.5 compile
print_info<PublicFoo>("PublicFoo");
// g++ 5.2.1 fails to compile has_foo, clang 3.5 compiles fine
print_info<ProtectedFoo>("ProtectedFoo");
// g++ 5.2.1 fails to compile, clang 3.5 compiles fine
print_info<PrivateFoo>("PrivateFoo");
// both g++ 5.2.1 and clang 3.5 compile
print_info<NoFoo>("NoFoo");
return 0;
}
Why do I want to do this?
Skip this if you don't want to know the details. I just wrote this in case you were either shocked by the idea of me trying to detect protected members and/or curious about why I asked this question.
I was writing some kind of iterator template classes built out of other iterators and I got tired of writing multiple specializations depending on whether these iterators meet some requirements (ForwardIterator, BidirectionalIterator, RandomAccessIterator... although my iterators actually meet some relaxed versions of these concepts, they are kind of "proxy iterators" but it's not really relevant here).
For instance, if I only use random access iterators, my new custom iterator could (and should) also be some kind of random access iterator, hence implement operator+=, operator+, operator-=, operator-, operator<, operator>, operator<= and operator>=. However, some of these operators can easily be deduced from others, and they should only be defined if all the iterator I use are random access iterators.
I finally thought I'd just make something to provide default implementations if available. However, I wasn't really fond of the std::allocator_traits way as it wouldn't be very handy and readable with iterators (plus, I wouldn't be able to use them with some standard utilities).
The design I finally choose consists in having a template class which will build a full-fledged iterator out of a minimal implementation (for instance containing only the operator+=, operator==, operator* and operator> definitions) by having an inheritance chain of "mixins" (whose ancestor is my minimal iterator) detecting whether the functions/methods they need are available in their base class and defining the default methods if they are.
There is a subtility though. Sometimes I want to return a reference to the final iterator (for instance in Iterator& operator++()). If it's a method I redefine, I can easily solve that with CRTP and a static_cast, but what if my mixins don't touch that method at all?
I figured I should probably forbid the use of any method I haven't touched and inherit my minimal iterator with the protected access specifier... but now then my traits fail to detect the availability of some protected methods.
Therefore, I'd like to have traits able to detect whether some members are available with either public or protected visibility.

Resources