只特化一个类模板的某一个成员函数
有类定义如下
template<class T, unsigned B>
class Base
{
//应被特化的函数
void Func(){}
};
现在只想在模板参数B为16时对函数Func进行特化,应该怎么做?
搜了半天也没找到可行的解决方案,希望大家帮帮忙,谢谢
[解决办法]
答案我记得写在《C++ templates》上,自己认真翻翻吧。
我记得是:不可以。但是,我听说部分编译器扩展支持。
[解决办法]
class A
{
public:
A(){}
~A(){}
template <class T>
void func(T t) {cout << t;}
}
int main()
{
A a;
a.func(100);
return 0;
}
[解决办法]
template<class T, unsigned B>
class Base
{
public:
void Func()
{
if (B == 16)
{
cout << "helloworl";
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Base<int,16> base;
base.Func();
}
//输出helloworld
[解决办法]
哦,这样啊。那得复杂点,试试下面这个吧。
#include <iostream>
namespace
{
template <bool,typename = void> struct enable_if { };
template <typename T> struct enable_if<true,T> { typedef T type; };
}
template<class T, unsigned B>
struct Base
{
template <unsigned N = B>
typename ::enable_if<16!=N>::type
Func () { std::cout << "primary" << std::endl; }
template <unsigned N = B>
typename ::enable_if<16==N>::type
Func () { std::cout << "specialization" << std::endl; }
};
int main ()
{
{
Base<int,0> b;
b.Func();
}
{
Base<int,16> b;
b.Func();
}
return 0;
}
[解决办法]
默认函数模板参数需要c++0x的支持。
常规的,不过很别扭,毕竟是反的。
template <class T, unsigned B> class Base;
template <class T> class Base<T, 16> { };
template <class T, unsigned B> class Base : public Base<T, 16> { };
[解决办法]
内部函数对象的话,如果要访问外部对象成员,又得多费手脚了。
传统的switch-case反倒是最一目了然的方法。
[解决办法]
解决“方案”离问题本身越来越远,越来越复杂,也就越来越丑陋。
[解决办法]
怎么说呢,刚才确实编译通过了,还运行了
如果说
template<class T, unsigned B>错误的话,那这个呢?
class SpecialValue
{
public:
void Func();
};
template<class T, unsigned B>
void SpecialValue<T,B>::Func()
{
printf("Template Specialization Normal\n");
}
template<class T>
void SpecialValue<T,16>::Func()
{
printf("Template Specialization Value:16\n");
}
template<class T>
class SpecialType
{
public:
void Func();
};
template<class T>
void SpecialType<T>::Func()
{
printf("Template Specialization Type::Normal\n");
}
template<>
void SpecialType<long>::Func()
{
printf("Template Specialization Type::long\n");
}
[解决办法]
嗨,那你用这个吧。试了一下,连 VS2010 都能编译了。
#include <iostream>
namespace
{
template <bool,typename T,typename> struct conditional { typedef T type; };
template <typename T,typename U> struct conditional<false,T,U> {typedef U type; };
}
template<class T, unsigned B>
struct Base
{
void Func ()
{
typedef typename ::conditional<B!=16,primary_t,spec_t>::type type;
Func_impl(type());
}
private:
struct primary_t { };
struct spec_t { };
void Func_impl (primary_t) { std::cout << "primary" << std::endl; }
void Func_impl (spec_t ) { std::cout << "specialization" << std::endl; }
};
int main ()
{
{
Base<int,0> b;
b.Func();
}
{
Base<int,16> b;
b.Func();
}
return 0;
}
Func_impl 是普通成员函数,应该都你玩的了。