0

I'm getting my feet wet with aliasing in templated classes, and haven't been able to compile the following code:

template <class T> using item_ptr = std::shared_ptr<T>;
class Container
{
    std::vector<item_ptr> list;
};

I get two compile errors, a type-value mismatch at argument 1 in template parameter list, and a template argument 2 is invalid. However, if I write the following code instead:

template <class T> //using item_ptr = std::shared_ptr<T>;
class Container
{
    std::vector<std::shared_ptr<T>> list;
};

then it compiles without errors. According to my understanding, these two statements should do the same thing. What am I not understanding correctly?

  • 2
    Voting to close as a typo. `item_ptr` is still a template so you need `item_ptr` just like you do with `shared_ptr` – NathanOliver Jun 29 '20 at 15:42
  • 1
    _"According to my understanding, these two statements should do the same thing."_ - Then why do you use them differently? You provide a template parameter to `std::shared_ptr`, but not to `item_ptr` ;) – Lukas-T Jun 29 '20 at 15:42
  • How could the compiler possibly know what type of `item_ptr` you want to instantiate in `Container`, when you don't tell it? I don't know that this is a typo, but it sure is a thinko. Did you perhaps mean something like `using item_ptr = std::shared_ptr`? – underscore_d Jun 29 '20 at 15:54
  • @underscore_d Isn't `item_ptr` just a `shared_ptr` to a `T` object now? So couldn't `item_ptr` only be of type `T`? – Jarom Allen Jun 29 '20 at 16:02
  • @JaromAllen The `template ` only applies to the `using` alias declaration. It doesn't apply to the `Container`. Not that just `vector` would be valid even if the `Container` did have a `template` line. They _both_ need those, and the usage of the alias must provide any template arguments it requires. @bipll already showed this – underscore_d Jun 29 '20 at 16:04

2 Answers2

1
template <class T> using item_ptr = std::shared_ptr<T>;

template <class T> class Container
{
    std::vector<item_ptr<T>> list;
};
underscore_d
  • 6,309
  • 3
  • 38
  • 64
bipll
  • 11,747
  • 1
  • 18
  • 32
0

if you want to use aliasing in the class, then define in the class:

template<class T>
class Container
{    
     using item_ptr = std::shared_ptr<T>;        
     std::vector<item_ptr> list;  
   
};
AR Hovsepyan
  • 107
  • 3