Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template deduction guide doesn't seem to be working

Following 'C++ Templates the Complete Guide', I wrote following code:

#include <vector>
#include <cassert>
#include <string>

template <typename T, typename Cont = std::vector<T>>
class Stack
{
    public:
        Stack() = default;

        Stack(T elem) :
            elems({std::move(elem)})
        { }

        auto push(T const& elem)       -> void;
        auto pop()                     -> void;
        auto top()               const -> T const&;
        auto empty()             const -> bool
        {
            return elems.empty();
        }

    private:
        Cont elems;
};

Stack(char const*) -> Stack<std::string>;

template <typename T, typename Cont>
auto Stack<T, Cont>::push(T const& elem) -> void
{
    elems.push_back(elem);
}

template <typename T, typename Cont>
auto Stack<T, Cont>::pop() -> void
{
    assert(!elems.empty());
    elems.pop_back();
}

template <typename T, typename Cont>
auto Stack<T, Cont>::top() const -> T const&
{
    assert(!elems.empty());
    return elems.back();
}

And used template class Stack in function main as follows:

auto main() -> int
{
    Stack stack_string {"hello"};
    std::cout << stack_string.top().size() << std::endl;
}

I assumed that due to 'template deduction guide' I provided with, the concrete type was Stack<std::string, std::vector<std::string>>

But compiler (Visual Studio 15 2017 with C++17) produced error saying that return type of Stack::top was const char *const

How do I make 'template deduction guide' works with const char* type?

like image 960
xvnm Avatar asked Aug 09 '18 06:08

xvnm


1 Answers

At least some versions of MSVC require:

template<std::size_t N>
Stack(char const(&)[N]) -> Stack<std::string>;

as it appears it doesn't "decay" the array into a pointer before doing deduction guides.

Live example.

like image 156
Yakk - Adam Nevraumont Avatar answered Nov 12 '22 20:11

Yakk - Adam Nevraumont