0%

Explicit specialization of template class member function in C++

StackOverFlow看到的一個範例。

lang: cpp
1
2
3
4
5
6
7
8
9
struct Functor {
template <typename T>
void function() {}
template <>
void function<int>() {}
};
Functor functor;
functor.function<char>();
functor.function<int>();

同樣的code,在gcc和clang編譯失敗,不過VC可以,同樣根據StackOvewflow的說法,這是VC的一個非標準Extension。

要模擬這個方案,可以靠function overloading來做。

lang: cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <typename T>
struct DummyIdentity {
typedef T type;
};
struct Functor {
template <typename T>
void function() {
function(DummyIdentity<T>());
}
private:
template <typename T>
void function(DummyIdentity<T>) {}
void function(DummyIdentity<int>) {}
};