C++ single template specialisation with multiple template parameters -
hallo!
i specialise 1 of 2 template types. e.g. template <typename a, typename b> class x
should have special implementation single function x<float, sometype>::somefunc()
.
sample code:
main.h:
#include <iostream> template <typename f, typename i> class b { public: void somefunc() { std::cout << "normal" << std::endl; }; void somefuncnotspecial() { std::cout << "normal" << std::endl; }; }; template <typename i> void b<float, i>::somefunc();
main.cpp:
#include <iostream> #include "main.h" using namespace std; template <typename i> void b<float, i>::somefunc() { cout << "special" << endl; } int main(int argc, char *argv[]) { b<int, int> b1; b1.somefunc(); b1.somefuncnotspecial(); b<float, int> b2; b2.somefunc(); b2.somefuncnotspecial(); }
compilation fails class b
. true, not possible in c++ in way? best workaround?
[edit]
template <float, typename i> void b<float, i>::somefunc();
leads main.h:26: error: ‘float’ not valid type template constant parameter
template <typename i> void b<float, i>::somefunc();
leads main.h:27: error: invalid use of incomplete type ‘class b’
and i'm using gcc.
[edit]
i don't want specialise whole class, there other functions don't have specialisation.
you have provide partial specialization of class template b
:
template <typename i> class b<float, i> { public: void somefunc(); }; template <typename i> void b<float, i>::somefunc() { ... }
you can define somefunc
inside specialization.
however, if want specialize function, , not class e. g.
template <typename f, typename i> void somefunc(f f, i) { somefuncimpl::act(f, i); } template <typename f, typename i> struct somefuncimpl { static void act(f f, i) { ... } }; // partial specialization template <typename i> struct somefuncimpl<float, i> { static void act(float f, i) { ... } };
but can't specialize function template without trick.
Comments
Post a Comment