0

The constructor takes T by value, so string literals will decay to char const*.

With the deduction guide Stack(char const*) -> Stack<std::string>,
I expect both cases to work.

Why the second argument deduction Stack ss2 = "string literal" does not?

#include<vector>
#include<string>

template<typename T>
class Stack {
    std::vector<T> elems;
public:
    Stack() = default;
    Stack(T elm) : elems({std::move(elm)}) { }
};

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

void test() {
    Stack ss1 { "works fine."};
    // error: conversion from 'const char [15]' to
    // non-scalar type 'Stack<std::__cxx11::basic_string<char> >' 
    // requested
    Stack ss2 = "compile error!"; 
}

Compiler explorer : https://godbolt.org/g/z3PaBp

cpplearner
  • 13,776
  • 2
  • 47
  • 72
Amin Roosta
  • 1,080
  • 1
  • 11
  • 26

1 Answers1

0

Stack ss2 = "compile error!";

This tries to:

  • Convert the string literal (which is an array of characters, char[15]) into a temporary string

  • Convert the temporary string to Stack

This fails for this reason:

  • An implicit conversion sequence can't involve more than one user-defined conversion. Two are need

See the complete answer to a duplicate question here error: conversion from 'const char [5]' to non-scalar type in c++

Amin Roosta
  • 1,080
  • 1
  • 11
  • 26