Phorce
Phorce

Reputation: 4642

C++ template for class declarations

So, I can do the following:

template<typename T>
void printValue(T theValue)
{
     std::cout << theValue;
}

int main()
{
   /.....
   int value = 5; 
   printValue(value); 

   return 0;
}

But if I want to do the following for a class:

template<class Type_T>
class Foo {

    public:
       template<typename Inverse>
       Foo(Inverse begin, Inverse end)
         : values(begin, end)
       {



       }

    protected:

       std::vector<Type_T> values;
};

int main() {

    std::vector<int> va = {1, 2, 3, 4, 5, 6};

    Foo<int> f(va.begin(), va.end());

    return 0;
}

I have to state the type. Is there a way for the compiler to be able to decide on the type, by knowing the type of iterator that is being passed through?

Upvotes: 0

Views: 49

Answers (1)

David G
David G

Reputation: 96810

You can create a helper function make_foo() which deduces the type from the argument given:

template<typename U>
Foo<typename U::value_type> make_foo(U first, U last)
{
    return { first, last };
}

auto f = make_foo(va.begin(), va.end());

Upvotes: 6

Related Questions