rtp*_*pax 7 c++ templates types
我最近正在开展一个项目,并希望在执行标准以外的操作时优先考虑某些类型.为此,我试图以某种方式使用模板来确定正在使用的数据类型.我写的清楚的代码不起作用,但它可以了解我正在尝试做的事情
#include <iostream>
template <type1,type2>
typename determine(type1 a, type2 b)
{
if (typeid(type1) == typeid(int) || typeid(type2) == typeid(int))
return int;
else return double;
}
int main()
{
int a = 3;
double b = 2;
std::cout << (static_cast<determine(a, b)>(a) / static_cast<determine(a, b)>(b)) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法确定返回我实际可以用来决定使用什么数据类型的东西?
您可以使用模板元编程技术来实现目标.
template <typename T1, typename T2> struct TypeSelector
{
using type = double;
};
template <typename T1> struct TypeSelector<T1, int>
{
using type = int;
};
template <typename T2> struct TypeSelector<int, T2>
{
using type = int;
};
template <> struct TypeSelector<int, int>
{
using type = int;
};
Run Code Online (Sandbox Code Playgroud)
然后,使用:
int main()
{
int a = 3, b = 2;
using type1 = TypeSelector<decltype(a), decltype(b)>::type;
std::cout << (static_cast<type1>(a) / static_cast<type1>(b)) << std::endl;
float c = 4.5f;
using type2 = TypeSelector<decltype(a), decltype(c)>::type;
std::cout << (static_cast<type2>(a) / static_cast<type2>(c)) << std::endl;
using type3 = TypeSelector<decltype(c), decltype(a)>::type;
std::cout << (static_cast<type3>(c) / static_cast<type3>(a)) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
我很确定你可以通过以下方式完成这个std::conditional和一些std::is_same限定符的逻辑组合||:
#include <iostream>
#include <type_traits>
template<class T1, class T2>
using determine = typename std::conditional<
std::is_same<T1,int>::value || std::is_same<T2,int>::value,
int, double>::type;
int main()
{
int a = 3;
double b = 2;
long c = 3L;
using type1 = determine<decltype(a),decltype(b)>;
std::cout << (static_cast<type1>(a) / static_cast<type1>(b)) << std::endl;
using type2 = determine<decltype(b),decltype(c)>;
std::cout << (static_cast<type2>(b) / static_cast<type2>(c)) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4213 次 |
| 最近记录: |