简体   繁体   中英

Specialization of member function of a template class in C++

I would like to create a template class foo, and have one of its member function test() be specialized according to the template type of foo. M first attempt was to include the code in the header file defining foo:

template<typename Type>
class foo
{
    foo()
    ~foo()
    test()
};

template<>
foo<float>::test()
{ code ... };

The problem is that if I compile and link multiple files using this header, I get an error of multiple definition.

I also tried to declare the specialization in the header, so the compiler knows it should not generate the templated code. I then put the specialized definition in a separate C++ file to be compiled. The header then looked like:

template<typename Type>
class foo
{
    foo()
    ~foo()
    test()
};

template<>
foo<float>::test();

But I then got an undefined reference error.

How should I organize the declaration and definition of the specialized member function ?

Put the declaration in the header file, and the definition in a source file.

Since the function is fully specified by the declaration, the definition can be in any translation unit. linked with the application.

Or make the function definition inline in the header file.

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