Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template type deduction in container initialisation

Tags:

c++

I understand that a template type parameter can be defaulted, however, this doesn't work when I attempt to construct a std::vector without supplying the template argument:

#include<vector>

template <typename Int = int>
struct integer{
    Int i;
};

int main(){

    integer num;

    std::vector<integer> vec;

    return 0;
}

This code returns a type value mismatch (compiler explorer link). Is it possible to fix this without writing std::vector<integer<int>>

like image 489
Daniel Meilak Avatar asked Dec 30 '22 11:12

Daniel Meilak


1 Answers

If you have a function with a default parameter:

 int foo(int bar=0);

To call this function you still have to write:

 int n=foo();

attempting to write int n=foo; will not work, of course. For the same reason if your template's parameters are defaulted you still have to use

  integer<>

to instantiate the template instead of

  integer
like image 190
Sam Varshavchik Avatar answered Jan 11 '23 22:01

Sam Varshavchik