简体   繁体   中英

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?

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()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM