[英]c++11 template specialisation wrapper
我想在c ++ 11中做這樣的事情,但我不知道該怎么做或要對谷歌做什么:它的目標是在返回類型上模擬多態性,這里是示例代碼,用以解釋我想做的事情
enum foo : int
{
bar = 1,
baz = 2
};
class Common
{
public:
Common(){}
~Common(){}
foo _val;
};
class A : public Common
{
A() :_val(foo::bar){}
virtual ~A(){}
int func(){return 0;}
};
class B : public Common
{
B() :_val(foo::baz){}
~B(){}
double func(){return 60.55;}
};
template <foo V>
auto wrapper(Common * val)
{
return wrapper<V>(val);
}
template <foo::bar>
A * wrapper(Common * val)
{
return (A*)val;
}
template <foo::baz>
A * wrapper(Common * val)
{
return (B*)val;
}
void leFunc(Common * t)
{
auto val = wrapper<t::_val>(&t)->func();
}
int main()
{
std::list<Common *> lst = {new A, new B};
for (auto & e : lst)
leFunc(e);
}
編輯:我想做的一些真實的例子:想法是有這樣的電話:
int i = wrapper<1>(myInterface &);
double k = wrapper<2>(myInterface &);
std::list<float> i = wrapper<3>(myInterface &);
使用存儲在界面中的模板特化(值)編輯代碼以更精確
我不確定您到底想要什么。 也許像這樣 。 下面是src。
#include <iostream>
using namespace std;
enum Gender{
MALE = 1, FEMALE = 2, UNKNOWN = 3
};
template <Gender genderValue>
struct CommonPerson{
virtual Gender getGender()const{ return genderValue; }
virtual ~CommonPerson(){};
};
struct Male: public CommonPerson<MALE>{};
struct Female: public CommonPerson<FEMALE>{};
string toString(const Gender& g){
if(g == MALE) return "MALE";
else return "FEMALE";
}
template<typename T>
void printGender(const T& person){
std::cout << toString(person.getGender()) << endl;
}
int main(){
Male male;
Female female;
printGender(male);
printGender(female);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.