Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can template deduction guides call constexpr functions?

I have my own fixed-size array type I want to be constexpr constructible from an std::initializer_list without having to explicitly define the size template argument.

I thought I'd be able to use a template deduction guide but it looks like it's not treating std::initializer_list::size() as a constexpr function for it.

Here's an example of trying to make a deduction guide for std::array (which is similar to my type and has the same problem):

namespace std
{
    template<typename T> array(initializer_list<T> initialiserList) -> array<T, initialiserList.size()>;
}
static constexpr std::array myArray = {1,2,3};
static constexpr std::array myArray2 = {{1,2,3}};

I've tried on MSVC and Clang, both give roughly the same errors: myArray has an error complaining about too many arguments to the function. myArray2 says "substitution failure [with T = int]: non-type template argument is not a constant expression"

I tried putting constexpr in front of the deduction guide or the function argument but neither appears to be allowed, so it appears that the deduction guide is invalid even though it should work fine in a constexpr context.

Is there a way to make this work without going down the make_array() route?

like image 256
Blake Preston Avatar asked Jan 06 '19 22:01

Blake Preston


People also ask

What is template deduction?

Template argument deduction is used when selecting user-defined conversion function template arguments. A is the type that is required as the result of the conversion. P is the return type of the conversion function template.

What can be Constexpr?

constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.

What is type deduction c++?

Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. In C++, the auto keyword(added in C++ 11) is used for automatic type deduction.


1 Answers

You can do:

template <class T, class... U>
array(T, U...) -> array<T, 1 + sizeof...(U)>;

The problem is not that you cannot call constexpr functions in deduction guides. You can. This example is ridiculous, but works:

constexpr size_t plus_one(size_t i) { return i + 1; }

template <class T, class... U>
array(T, U...) -> array<T, plus_one(sizeof...(U))>;

The problem is that function parameters are not constexpr objects, so you cannot invoke constexpr member functions on them if those member functions read kind of local state.

like image 111
Barry Avatar answered Sep 17 '22 15:09

Barry