How to explicitly instantiate a template for all members of MPL vector in C++?

后端 未结 6 568
日久生厌
日久生厌 2021-02-01 05:53

Consider the following header file:

// Foo.h
class Foo {
    public: 
        template 
        void read(T& value);
};

I

6条回答
  •  一生所求
    2021-02-01 06:21

    I don't think it is necessary, nor is it possible.

    You can directly use (call) the function Foo:read(bar), for variable bar of any type, as long as the type is well-defined in your template function implementation. The compiler will automatically morph your argument into type "T".

    For example:

    template 
    Foo::read(T & var)
    {
        std::cin >> var;
    }
    

    T is well-defined when T is a streaming type supported by cin.

    The example will be self-contained, if "Foo::" is removed. I mean, for "Foo::", you should have somewhere defined a class Foo, or a namespace Foo, to make it work.

    Yet please note that template should always go inside a .h file, not a .cpp file (just search the web with keyword "c++ template can not be implemented in cpp file"

提交回复
热议问题