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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With