通過使用 c 14 或 c 11,我們是否有一種優雅的方法來完成以下任務?成員數量和操作型別由模板輸入值 'count' 決定
template<int count>
class show{
public:
run(){
if (count == 1){
int x;
} else if(count ==2){
int x, y;
}else if(count ==3){
int x, y, z;
}
if (count == 1){
printf("res: %d \n", x);
} else if(count ==2){
printf("res: %d \n", x y);
}else if(count ==3){
printf("res: %d \n", x y z);
}
}
};
更新:在這種情況下,我們可以使用部分專業化或與模板相關的東西嗎?
uj5u.com熱心網友回復:
是的,您可以使用專業化:
template<int count>
class show;
template<>
class show<1>{
int x;
public:
show(int _x):x{_x}{}
void run(){
std::cout << "val of x " << x << std::endl;
}
};
template<>
class show<2>{
int x,y;
public:
show(int _x, int _y):x{_x}, y{_y}{}
void run(){
std::cout << "add " << x y << std::endl;
}
};
但你也可以讓它更通用:
template <int count>
class simply
{
std::array<int, count> arr;
public:
template < typename ... T >
simply( T ... in ): arr{ in... } {}
void run()
{
std::cout << [this](){ int sum=0; for( auto el: arr ){ sum =el; } return sum; }() << std::endl;
}
};
要使用上述所有內容:
int main() {
show<1> s1(10);
show<2> s2(100,200);
s1.run();
s2.run();
simply<4> si( 1,2,3,4 );
si.run();
}
備注:您應該添加一些更多的東西來simply檢查所有型別為 int 的引數與 sfinae 或static_assert. 但他是另一個問題......
uj5u.com熱心網友回復:
在您的情況下,陣列 ( std::array) 似乎合適:
template <std::size_t count>
class show
{
public:
std::array<int, count> data{};
// ...
void run()
{
const int sum = std::accumulate(data.begin(), data.end(), 0);
printf("res: %d \n", sum);
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/385152.html
上一篇:is_trivially_copyable在我實作的建構式和默認建構式之間的行為不同
下一篇:不同的模板簽名
