Why does std::forward discard constexpr-ness? - c++

Being not declared constexpr, std::forward will discard constexpr-ness for any function it forwards arguments to. Why is std::forward not declared constexpr itself so it can preserve constexpr-ness?
Example: (tested with g++ snapshot-2011-02-19)
#include <utility>
template <typename T> constexpr int f(T x) { return -13;}
template <typename T> constexpr int g(T&& x) { return f(std::forward<T>(x));}
int main() {
constexpr int j = f(3.5f);
// next line does not compile:
// error: ‘constexpr int g(T&&) [with T = float]’ is not a constexpr function
constexpr int j2 = g(3.5f);
}
Note: technically, it would be easy to make std::forward constexpr, e.g., like so (note that in g std::forward has been replaced by fix::forward):
#include <utility>
namespace fix {
/// constexpr variant of forward, adapted from <utility>:
template<typename Tp>
inline constexpr Tp&&
forward(typename std::remove_reference<Tp>::type& t)
{ return static_cast<Tp&&>(t); }
template<typename Tp>
inline constexpr Tp&&
forward(typename std::remove_reference<Tp>::type&& t)
{
static_assert(!std::is_lvalue_reference<Tp>::value, "template argument"
" substituting Tp is an lvalue reference type");
return static_cast<Tp&&>(t);
}
} // namespace fix
template <typename T> constexpr int f(T x) { return -13;}
template <typename T> constexpr int g(T&& x) { return f(fix::forward<T>(x));}
int main() {
constexpr int j = f(3.5f);
// now compiles fine:
constexpr int j2 = g(3.5f);
}
My question is: why is std::forward not defined like fix::forward ?
Note2: this question is somewhat related to my other question about constexpr std::tuple as std::forward not being constexpr is the technical reason why std::tuple cannot be created by calling its cstr with rvalues, but this question here obviously is (much) more general.

The general answer is that the C++ committee's Library Working Group have not done an exhaustive trawl through the working draft looking for opportunities to use the new core facilities. These features have been used where people have had the time and inclination to look at possible uses, but there is not the time for exhaustive checking.
There are some papers regarding additional uses of constexpr in the works, such as those in the November 2010 mailing.

Related

How to produce compiler error if default template is used?

Using template specialization, I've written a series of functions all having the same name and taking the same argument type, but returning data of the type specified by the template parameter:
template<typename T> T f (int x); // Purposefully unimplemented.
template<> inline uint8_t f<uint8_t> (int x) { return f8 [x]; }
template<> inline uint16_t f<uint16_t>(int x) { return f16 [x]; }
template<> inline uint32_t f<uint32_t>(int x) { return f32 [x]; }
template<> inline uint64_t f<uint64_t>(int x) { return f64 [x]; }
Then I can write code like:
uint32_t a = f<uint32_t>(3);
uint64_t b = f<uint64_t>(7);
I've purposefully left the default template unimplemented to produce a linker error if someone tries to use a version of f for anything other than the specialized types for which I've defined it.
I have two questions:
1) Is there some way I can use static_assert() (or whatever) to produce a compile error (instead of a linker error) if someone tries to use the default template that's more friendly than what I get now: undefined reference to `int f(int)'?
2) Is there some way to do this with templates that maintains the same interface to the programmer, but doesn't require template specialization? (I.e., is there some way to avoid a default template altogether?)
namespace fimpl{
template<class T>struct tag_t{};
template<class T>
void fimpl(tag_t<T>, int x)=delete;
}
template<typename T> T f (int x){ using fimpl::fimpl; return fimpl(fimpl::tag_t<T>{}, x); }
now don't specialize; override.
namespace fimpl{ inline uint8_t fimpl(tag_t<uint8_t>, int x) { return f8 [x]; } }
namespace fimpl{ inline uint16_t fimpl(tag_t<uint16_t>, int x) { return f16 [x]; } }
namespace fimpl{ inline uint32_t fimpl(tag_t<uint32_t>, int x) { return f32 [x]; } }
namespace fimpl{ inline uint64_t fimpl(tag_t<uint64_t>, int x) { return f64 [x]; } }
This uses tag dispatching to pick which override instead of using specialization.
If no explicit specialization is found, the =delete template is picked and youmget a compiler error immediately.
Amusingly, if you wanted to extend this with new types, say namespace lib{ struct bigint; } you can put a fimpl(fimpl::tag_t<bigint>, int) overload in namespace lib and it would work. I doubt you'll need that.
You can also do away with f as a template if you are ok with f(tag<uint8_t>, 7) instead of f<uint8_t>(7). Just get rid of fimpl namespace (moving stuff out of it), rename fimpl::fimpl to just f, remove =deleteed template function, add template<class T> constexpr tag_t<T> tag{};. But the syntax is a bit different at point of call.
Is there some way I can use static_assert (or whatever) to produce a compile error (instead of a linker error) if someone tries to use the default template that's more friendly than what I get now: undefined reference to `int f(int)'?
I think the better solution is the one suggested by Passer By in a comment:
template<typename T> T f (int x) = delete;
But if you really want to use a static_assert()... I suppose you can try something as follows
template<typename T>
T f (int x)
{
static_assert( sizeof(T) == std::size_t(-1), "f()!" );
return {};
}
Is there some way to do this with templates that maintains the same interface to the programmer, but doesn't require template specialization? (I.e., is there some way to avoid a default template altogether?)
Isn't clear to me what do exactly want.
You don't want specialization and you want avoid default template?
Supposing that you want only the default template that is available only for a specific set of types, I suppose you can use SFINAE.
To make an example, the following f() is enabled only if T is an integral type.
template<typename T>
typename std::enable_if<std::is_integral<T>{}, T>::type f (int x)
{ return x; }
The following is a full compiling example
#include <iostream>
#include <type_traits>
template<typename T>
typename std::enable_if<std::is_integral<T>{}, T>::type f (int x)
{ return x; }
int main ()
{
auto f16 = f<std::uint16_t>(0);
auto f32 = f<std::uint32_t>(0);
static_assert( std::is_same<decltype(f16), std::uint16_t>{}, "!" );
static_assert( std::is_same<decltype(f32), std::uint32_t>{}, "!" );
// compilation error
// auto fd = f<double>(0);
}

using result of constexpr function as a template parameter (clang vs gcc)

Please take a look at the code below, sorry that is a bit lengthy, but I did my best to reproduce the problem with a minimum example (there is also a live copy of it). There I basically have a metafunction which returns the size of string literal, and constexpr function which wraps it. Then when I call those functions in a template parameter gcc (5.4, 6.2) is happy with it, but clang (3.8, 3.9) barfs with "non-type template argument is not a constant expression" in test body on strsize(s). If I replace with a str_size<S> both compilers are happy. So the questions are:
whether that is a problem with clang, or my code?
What is the way to make it compile on both clang and gcc with constexpr function?
template<size_t N> using string_literal_t = char[N];
template<class T> struct StrSize; ///< metafunction to get the size of string literal alikes
/// specialize StrSize for string literals
template<size_t N>
struct StrSize <string_literal_t<N>>{ static constexpr size_t value = N-1; };
/// template variable, just for convenience
template <class T>
constexpr size_t str_size = StrSize<T>::value;
/// now do the same but with constexpr function
template<class T>
constexpr auto strsize(const T&) noexcept-> decltype(str_size<T>) {
return str_size<T>;
}
template<class S, size_t... Is>
constexpr auto test_helper(const S& s, index_sequence<Is...>) noexcept-> array<char, str_size<S>> {
return {s[Is]...};
}
template<class S>
constexpr auto test(const S& s) noexcept-> decltype(auto) {
// return test_helper(s, make_index_sequence<str_size<S>>{}); // this work in both clang and gcc
return test_helper(s, make_index_sequence<strsize(s)>{}); // this works only in gcc
}
auto main(int argc, char *argv[])-> int {
static_assert(strsize("qwe") == 3, "");
static_assert(noexcept(test("qwe")) == true, "");
return 0;
}
Clang is correct here. The problem is in the code and in GCC, which erroneously accepted it. This was fixed in GCC 10: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66477
According to the standard expr.const#5.12:
An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine, would evaluate one of the following:
...
an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either
it is usable in constant expressions or
its lifetime began within the evaluation of E;
And here the compiler is unable to verify the validity of reference in test(const S& s).
Actually there is a nice article to read here: https://brevzin.github.io/c++/2020/02/05/constexpr-array-size/
As to your other question:
What is the way to make it compile on both clang and gcc with constexpr function?
You can replace references with std::array passed by value:
#include <array>
using namespace std;
template<class T> struct StrSize;
template<size_t N>
struct StrSize <array<char,N>>{ static constexpr size_t value = N-1; };
template <class T>
constexpr size_t str_size = StrSize<T>::value;
template<class T>
constexpr auto strsize(const T&) noexcept-> decltype(str_size<T>) {
return str_size<T>;
}
template<class S, size_t... Is>
constexpr auto test_helper(const S& s, index_sequence<Is...>) noexcept-> array<char, str_size<S>> {
return {s[Is]...};
}
constexpr auto test(array<char,4> s) noexcept-> decltype(auto) {
return test_helper(s, make_index_sequence<strsize(s)>{});
}
int main() {
static_assert(noexcept(test({"qwe"})) == true, "");
}
Demo: https://gcc.godbolt.org/z/G8zof38b1

C++11 Implicit conversion from initialization list to array parameter

In C++11, is it possible to do something similar to the following?
template<typename T, size_t N>
void foo(array<T, N> src) { ... }
...
foo({1, 2, 3})
I'm currently running GCC 4.8.
Yes, I managed to get the following work (since you allow something similar):
template<typename T, size_t N>
void foo(array<T, N> src) { ... }
...
foo('a', 'b');
foo(1, 2, 3);
Here is how:
#include <array>
#include <iostream>
#include <utility>
using namespace std;
template<typename T, unsigned long N>
void foo(array<T,N> src) {
for (auto e : src)
cout << e << endl;
}
template<class T, class... Tail>
auto make_array(T head, Tail... tail) -> std::array<T, 1 + sizeof...(Tail)>
{
std::array<T, 1 + sizeof...(Tail)> a = {{ head, tail ... }};
return a;
}
template<class T, class... Tail>
void foo(T&& head, Tail&&... values) {
foo(make_array(std::forward<T>(head), std::forward<Tail>(values)...));
}
int main() {
foo('a', 'b');
foo(1, 2, 3);
}
I have tested this with gcc 4.7.2 and with clang 3.4 (trunk 184647), they work as expected.
Here is an online version at Stacked-Crooked. However, this code fails to compile at Ideone. Since I was unable to figure out the options passed to the compiler at Ideone, I've given up on that site.
I have shamelessly stolen the make_array function from #Pavel Minaev's answer to the How to emulate C array initialization “int arr[] = { e1, e2, e3, … }” behaviour with std::array? question. The other make_array suggestions caused compile errors that I couldn't fix.
This make_array function has limitations, please read the entire post; in particular the discussion std::array - if only it knew its size on comp.lang.c++.moderated is referenced. Apparently, getting a reasonable make_array is quite tricky. I wouldn't recommend the simple-minded make_array in this answer to be used in production code.
You wouldn't have any problems if the size was a template argument to std::initializer_list. Hence the question Why is the size not a template argument of std::initializer_list?
Apparently not. The standard (14.8.2.5) calls this an non-deduced context;
In certain contexts, however, the value does not participate in type deduction, but instead uses the values of template arguments that were either deduced elsewhere or explicitly specified.
...
The non-deduced contexts are:
...
A function parameter for which the associated argument is an initializer list (8.5.4) but the parameter does not have std::initializer_list or reference to possibly cv-qualified std::initializer_list type.
Example:
template<class T> void g(T);
g({1,2,3}); // error: no argument deduced for T
EDIT: You can make the same thing work with std::vector, if you just use an initializer_list overload to make the deduction of the type work;
template<typename T>
void foo(const std::vector<T>& src) { ...your code here... }
template<typename T>
void foo(const std::initializer_list<T>& src) { foo(std::vector<T>(src)); }
foo({1,2,3}); // Compiles
...but sadly, since the size of initializer_list is not a template argument, I can't think of a way to make it deduce and forward the array size from the initializer_list in the same way as the type.
You could use an initializer list directly to achieve that syntax. e.g.:
#include <iostream>
#include <initializer_list>
void foo(std::initializer_list<int> il) {
for (auto i: il)
std::cout << i < std::endl;
}
int main() {
foo({1,2,3});
}
or make it more generic:
template <typename T>
void foo(std::initializer_list<T> il) {
...
It is possible with references to raw arrays:
template <typename T, size_t N>
void foo(T const (&x)[N]) {
// x is [1, 2, 3], N = 3
}
int main() {
foo({1, 2, 3});
return 0;
}
Note that the array must be declared const.

Passing an integer or a type as a template parameter?

Here is an example case of what I'm trying to do (it is a "test" case just to illustrate the problem) :
#include <iostream>
#include <type_traits>
#include <ratio>
template<int Int, typename Type>
constexpr Type f(const Type x)
{
return Int*x;
}
template<class Ratio, typename Type,
class = typename std::enable_if<Ratio::den != 0>::type>
constexpr Type f(const Type x)
{
return (x*Ratio::num)/Ratio::den;
}
template</*An int OR a type*/ Something, typename Type>
constexpr Type g(const Type x)
{
return f<Something, Type>(x);
}
int main()
{
std::cout<<f<1>(42.)<<std::endl;
std::cout<<f<std::kilo>(42.)<<std::endl;
}
As you can see, there are two versions of the f() function : the first one takes an int as a template parameter, and the second one takes a std::ratio. The problem is the following :
I would like to "wrap" this function through g() which can take an int OR a std::ratio as first template parameter and call the good version of f().
How to do that without writing two g() functions ? In other words, what do I have to write instead of /*An int OR a type*/ ?
Here's how I would do it, but I've changed your interface slightly:
#include <iostream>
#include <type_traits>
#include <ratio>
template <typename Type>
constexpr
Type
f(int Int, Type x)
{
return Int*x;
}
template <std::intmax_t N, std::intmax_t D, typename Type>
constexpr
Type
f(std::ratio<N, D> r, Type x)
{
// Note use of r.num and r.den instead of N and D leads to
// less probability of overflow. For example if N == 8
// and D == 12, then r.num == 2 and r.den == 3 because
// ratio reduces the fraction to lowest terms.
return x*r.num/r.den;
}
template <class T, class U>
constexpr
typename std::remove_reference<U>::type
g(T&& t, U&& u)
{
return f(static_cast<T&&>(t), static_cast<U&&>(u));
}
int main()
{
constexpr auto h = g(1, 42.);
constexpr auto i = g(std::kilo(), 42.);
std::cout<< h << std::endl;
std::cout<< i << std::endl;
}
42
42000
Notes:
I've taken advantage of constexpr to not pass compile-time constants via template parameters (that's what constexpr is for).
g is now just a perfect forwarder. However I was unable to use std::forward because it isn't marked up with constexpr (arguably a defect in C++11). So I dropped down to use static_cast<T&&> instead. Perfect forwarding is a little bit overkill here. But it is a good idiom to be thoroughly familiar with.
How to do that without writing two g() functions ?
You don't. There is no way in C++ to take either a type or a value of some type, except through overloading.
It is not possible to have a template parameter taking both type and non-type values.
Solution 1:
Overloaded functions.
Solution 2:
You can store values in types. Ex:
template<int n>
struct store_int
{
static const int num = n;
static const int den = 1;
};
template<class Ratio, typename Type,
class = typename std::enable_if<Ratio::den != 0>::type>
constexpr Type f(const Type x)
{
return (x*Ratio::num)/Ratio::den;
}
template<typename Something, typename Type>
constexpr Type g(const Type x)
{
return f<Something, Type>(x);
}
But with this solution you will have to specify g<store_int<42> >(...) instead of g<42>(...)
If the function is small, I advise you to use overloading.

C++ Forward non-template member function call to template function

I'd like to hide a std::tuple in my class 'Record' and provide an operator[] on it to access elements of the tuple. The naive code that does not compile is this:
#include <tuple>
template <typename... Fields>
class Record {
private:
std::tuple<Fields...> list;
public:
Record() {}
auto operator[](std::size_t n)
-> decltype(std::get<1u>(list)) {
return std::get<n>(list);
}
};
int main() {
Record<int, double> r;
r[0];
return 0;
}
g++ 4.6 says:
x.cc:13:32: error: no matching function for call to ‘get(std::tuple<int, double>&)’
x.cc:13:32: note: candidates are:
/usr/include/c++/4.6/utility:133:5: note: template<unsigned int _Int, class _Tp1, class _Tp2> typename std::tuple_element<_Int, std::pair<_Tp1, _Tp2> >::type& std::get(std::pair<_Tp1, _Tp2>&)
/usr/include/c++/4.6/utility:138:5: note: template<unsigned int _Int, class _Tp1, class _Tp2> const typename std::tuple_element<_Int, std::pair<_Tp1, _Tp2> >::type& std::get(const std::pair<_Tp1, _Tp2>&)
/usr/include/c++/4.6/tuple:531:5: note: template<unsigned int __i, class ... _Elements> typename std::__add_ref<typename std::tuple_element<__i, std::tuple<_Elements ...> >::type>::type std::get(std::tuple<_Elements ...>&)
/usr/include/c++/4.6/tuple:538:5: note: template<unsigned int __i, class ... _Elements> typename std::__add_c_ref<typename std::tuple_element<__i, std::tuple<_Elements ...> >::type>::type std::get(const std::tuple<_Elements ...>&)
Basically I'd like to call Record::operator[] just like on an array. is this possible?
The argument to get is a compile time constant. You cannot use a
runtime variable for this and you cannot have a single function that
returns the tuple members as your return type is going to be
wrong. What you can do is to abuse non-type argument deduction:
#include <tuple>
template<typename... Args>
struct Foo {
std::tuple<Args...> t;
template<typename T, std::size_t i>
auto operator[](T (&)[i]) -> decltype(std::get<i>(t)) {
return std::get<i>(t);
}
// also a const version
};
int main()
{
Foo<int, double> f;
int b[1];
f[b];
return 0;
}
This is so horrible, that I would never use it and it won't make much sense to users. I would just forward get through a template member.
I'll try to explain why I think why this is really evil: The return type of a function depends only on compile time facts (this changes slightly for virtual member functions). Let's just assume that non-type argument deduction were possible for some cases (the function call arguments are constexpr) or that we could build something that hides it reasonably well, your users wouldn't realize that their return type just changed and implicit conversion would do nasty things to them. Making this explicit safes some of the trouble.
The error message seems to be misleading, as the problem with your code is pretty much clear:
auto operator[](std::size_t n)
-> decltype(std::get<1u>(list)) {
return std::get<n>(list);
}
The template argument n to std::get must be a constant expression, but in your code above n is not a constant expression.
No.
It is not possible to use a parameter bound at runtime (such as a function parameter) to act as template parameter, because such need be bound at compile-time.
But let's imagine for a second that it was:
Record<Apple, Orange> fruitBasket;
Then we would have:
decltype(fruitBasket[0]) equals Apple
decltype(fruitBasket[1]) equals Orange
is there not something here that bothers you ?
In C++, a function signature is defined by the types of its arguments (and optionally the values of its template parameters). The return type is not considered and does not participate (for better or worse) in the overload resolution.
Therefore, the function you are attempting to build simply does not make sense.
Now, you have two alternatives:
require that all arguments inherit or be convertible to a common type, and return that type (which allows you to propose a non-template function)
embrace templates and require your users to provide specifically the index of the type they wish to use
I do not (and cannot) which alternative is preferable in your particular situation, this is a design choice you will have to make.
Finally, I will remark that you may be reasoning at a too low level. Will your users really need to access each field independently ? If they don't, you could provide facilities to apply functions (visitors ?) to each element in turn, for example.
I think Xeo had code which did this.
Here is my attempt which somewhat works. The problem is that [] is not a reference.
template<typename T, std::size_t N = std::tuple_size<T>::value - 1>
struct foo {
static inline auto bar(std::size_t n, const T& list)
-> decltype(((n != N) ? foo<T, N-1>::bar(n, list) : std::get<N>(list))) {
return ((n != N) ? foo<T, N-1>::bar(n, list) : std::get<N>(list));
}
};
template<typename T>
struct foo<T, 0> {
static inline auto bar(std::size_t n, const T& list)
-> decltype(std::get<0>(list)) {
return std::get<0>(list);
}
};
template <typename... Fields>
class Record {
private:
std::tuple<Fields...> list;
public:
Record() {
std::get<0>(list) = 5;
}
inline auto operator[](std::size_t n)
-> decltype(foo<decltype(list)>::bar(n, list)) {
return foo<decltype(list)>::bar(n, list);
}
};
int main() {
Record<int, double> r;
std::cout << r[0];
return 0;
}
As n is a template parameter, it should be known in compile time, but you want to pass it as a parameter in run-time.
Also, gcc 4.5.2 isn't happy due to this fact:
g++ 1.cpp -std=c++0x
1.cpp: In member function 'decltype (get<1u>(((Record<Fields>*)0)->Record<Fields>::list)) Record<Fields>::operator[](size_t)':
1.cpp:14:25: error: 'n' cannot appear in a constant-expression
If you're fine with a compile-time constant and still want to have the nice operator[] syntax, this is an interesting workaround:
#include <tuple>
template<unsigned I>
struct static_index{
static unsigned const value = I;
};
template <typename... Fields>
class Record {
private:
typedef std::tuple<Fields...> tuple_t;
tuple_t list;
public:
Record() {}
template<unsigned I>
auto operator[](static_index<I>)
-> typename std::tuple_element<
I, tuple_t>::type&
{
return std::get<I>(list);
}
};
namespace idx{
const static_index<0> _0 = {};
const static_index<1> _1 = {};
const static_index<2> _2 = {};
const static_index<3> _3 = {};
const static_index<4> _4 = {};
}
int main() {
Record<int, double> r;
r[idx::_0];
return 0;
}
Live example on Ideone. Though I'd personally just advise to do this:
// member template
template<unsigned I>
auto get()
-> typename std::tuple_element<
I, tuple_t>::type&
{
return std::get<I>(list);
}
// free function
template<unsigned I, class... Fields>
auto get(Record<Fields...>& r)
-> decltype(r.template get<I>())
{
return r.template get<I>();
}
Live example on Ideone.