Template specialization for a member function

What's the correct syntax to create a full template specialization of a member function? For instance consider:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct Tata {

    template <typename T>
    T get(int){
        return (T) 0;
    }

    template <>
    std::string get<std::string>(int);

};

template<>
std::string Tata<std::string>::get(int){
    return "Hello world!";
}

int main(int argc, const char *argv[]) {
    Tata t;
    cout << t.get<std::string>(3) << endl;
}


This raises several errors:
1
2
3
4
5
6
7
8
../cpp_helloworld.cpp:22:15: error: explicit specialization in non-namespace scope ‘struct Tata’
     template <>
               ^
../cpp_helloworld.cpp:23:37: error: template-id ‘get<std::__cxx11::string>’ in declaration of primary template
     std::string get<std::string>(int);
                                     ^
../cpp_helloworld.cpp:27:17: error: expected initializer before ‘<’ token
 std::string Tata<std::string>::get(int){


What's the correct way to declare & define the specialization for Tata.get<std::string>(int) ?

Thanks,
Dean
Last edited on
Place the explicit specialization of the member at namespace-scope (of the namespace where the class is defined.)
(Explicit specialization of a member at non-namespace-scope is not permitted.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <string>
#include <iostream>

struct Tata {

    template <typename T>
    T get(int){
        return (T) 0;
    }

    // template <>
    // std::string get<std::string>(int);

};

template<>
// std::string Tata<std::string>::get(int){
std::string Tata::get<std::string>(int){

    return "Hello world!";
}

int main() {
    
    Tata t;
    std::cout << t.get<std::string>(3) << '\n' ;
    std::cout << t.get<int>(3) << '\n' ;
}

http://coliru.stacked-crooked.com/a/023776903347d0c8
http://rextester.com/LAK61853
Topic archived. No new replies allowed.