注:これは問題の再投稿のようです: C++ - そのメソッドの部分的な仕様でテンプレート化されたクラス メソッドをオーバーロードする
C++ テンプレートの特殊化で発生している問題を単純なケースに要約しました。
これは単純な 2 パラメーターのテンプレート クラスで構成されており、ここで特化しThing
たいと思います。Thing<A,B>::doSomething()
B=int
#include <cstdio>
// A 3-parameter template class.
template <class A, class B>
class Thing
{
public:
Thing(A a, B b) : a_(a), b_(b) {}
B doSomething();
private:
A a_;
B b_;
};
// The generic case works as expected.
template <class A, class B>
B Thing<A,B>::doSomething()
{
return b_;
}
// This specialization does not work!
template <class A>
int Thing<A,int>::doSomething()
{
return b_+1;
}
int main() {
// Setup our thing.
Thing<double,int> thing(1.0,2);
// This doesn't compile - but works with the generic case.
printf("Expecting 3, and getting %i\n", thing.doSomething());
// Clean up.
return 0;
}
残念ながら、g++
エラーで終了します:
partial_specialization.cpp:30: error: invalid use of incomplete type ‘class Thing<A, int>’
partial_specialization.cpp:8: error: declaration of ‘class Thing<A, int>’
コンパイラはclang++
もう少し冗長ですが、同じ問題があります。
partial_specialization.cpp:30:19: error: nested name specifier 'Thing<A, int>::' for declaration does not
refer into a class, class template or class template partial specialization
int Thing<A,int>::doSomething()
~~~~~~~~~~~~~~^
partial_specialization.cpp:32:12: error: use of undeclared identifier 'b_'
return b_+1;
^
2 errors generated.
Thing
関数の部分的なテンプレートの特殊化は許可されていないことを読んで理解しましたが、この場合、クラスを部分的に特殊化していると思いました。
何か案は?
私がやったこと:受け入れられた回答によって提供されたリンクから決定される回避策:
template< class T >
inline T foo( T const & v ) { return v; }
template<>
inline int foo( int const & v ) { return v+1; }
// The generic case works as expected.
template <class A, class B>
B Thing<A,B>::doSomething()
{
return foo(b_);
}