# 如何编写计算整数和的可变参数模板类的通用版本

``````#include<iostream>

template<int...>

template<>
{
static constexpr int value = 0;
};

template<int i, int... tail>
{
static constexpr int value = i + add<tail...>::value;
};

int main()
{
}
``````

``````template<typename ...>

template<typename T, typename... args>
{
static constexpr T value = ??//T();//what to write here?
};
``````

AKL

``````template<auto& ...>
static constexpr auto value = 0;
};
template<auto& first, auto& ... others>
static constexpr auto value = first + add<others ...>::value;
};
``````

``````const auto v1 = 12; //int
const auto v2 = 54L; //long
const auto v3 = 3.25242; //double
const auto v4 = 75.7256L; //long double
``````

``````#include <iostream>
int main(){
std::cout << add<v1, v2, v3, v4>::value << std::endl;
}
``````

``````144.978
``````

``````class custom_type{
const float v;
//this one works too but the first is better for the purpose.
//float v;
public:
template<typename T>
constexpr custom_type(T v_):v(v_){}
template<typename T>
constexpr auto operator +(T o)const{
return o + 7345 + v ;
}
//this one works but the next one is  better for the purpose.
//operator auto()const{
//this one works too but the next one is more clear.
//constexpr operator auto()const{
template<typename T>
constexpr operator T()const{
return v;
}
};
``````

``````template<auto& ...>
static constexpr auto value = 0;
};
template<auto& first, auto& ... others>
static constexpr auto value = first + add<others ...>::value;
};

class custom_type{
const float v;
public:
template<typename T>
constexpr custom_type(T v_):v(v_){}
template<typename T>
constexpr auto operator +(T o)const{
return o + 7345 + v ;
}
template<typename T>
constexpr operator T()const{
return v;
}
};

const auto v1 = 12; //int
const auto v2 = 54L; //long
const auto v3 = 3.25242; //double
const auto v4 = 75.7256L; //long double
const custom_type v5 = 34.234; //custom_type

#include <iostream>
int main(){
std::cout << add<v1, v2, v3, v4, v5>::value << std::endl;
}
``````

``````7524.21
``````

``````template<const double& ...>
static constexpr double value = 0;
};
template<const double& first, const double& ... others>
static constexpr double value = first + add<others ...>::value;
};
``````

``````const double v1 = 12;
const double v2 = 54L;
const double v3 = 3.25242;
const double v4 = 75.7256l;
``````

0 条评论