Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

c++ - 'non-type partial specialization' when implementing a templated member function

In the following code i go on to create a struct with a templated get-function, and then a templated struct.

#include <iostream>

struct MyStruct
{
        int a;
        template<typename T> T getA();
};

template<typename T>
T MyStruct::getA<T>()
{
        return static_cast<T>(a);
}

template<typename T>
struct MyStructT
{
        int a;
        T getA();
};

template<typename T>
T MyStructT<T>::getA()
{
        return static_cast<T>(a);
}

int main(int argc, char* argv[])
{
        MyStruct s;
        s.a = 5;
        std::cout << s.getA<double>() << ' ' << s.getA<bool>() << std::endl;


        MyStructT<double> st;
        st.a = 5;
        std::cout << st.getA() << std::endl;
        return 0;
}

MyStructT compiles and works just fine, but MyStruct::getA<T> generates an error:

$ g++ --std=c++11 -o run *.cpp
test.cpp:10:21: error: non-type partial specialization ‘getA<T>’ is not allowed
   10 | T MyStruct::getA<T>()

The definitions are

question from:https://stackoverflow.com/questions/65897241/non-type-partial-specialization-when-implementing-a-templated-member-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For whatever reason the template type is not repeated within a name of the member function during the implementation, which is different to the way the name of the class/structure is handled. The correct way to implement it is:

template<typename T>
T MyStruct::getA()
{
        return static_cast<T>(a);
}

Here getA<T> is turned into simply getA.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...