Fly*_*Hat 10 c++ templates vector variadic-templates c++11
如何检查,在参数组的参数有两种类型float,double,整体或std::vector中上?
比如T={int, long, std::vector<double>}很好,
虽然T={int, long, std::vector<long double>} 不是,因为我们不允许std::vector成为long double类型.
我到目前为止
template<class ...T>
void foo(T... t)
{
static_assert(std::is_same<float, T...>::value
|| std::is_same<double, T...>::value
|| std::is_integral<T...>::value
/* || std::is_same<std::vector<float/double/integral>, T>::value ? */
, "unsupported type!");
}
Run Code Online (Sandbox Code Playgroud)
并不确定如何表达限制std::vector.
以float/double/integral某种方式重用检查会很好,这样我们就不需要输入两次了.就像是
bool basic_check = std::is_same<float, T...>::value
|| std::is_same<double, T...>::value
|| std::is_integral<T...>::value;
static_assert(basic_check
|| std::is_same<std::vector<basic_check>, T>
, "unsupported type!");
Run Code Online (Sandbox Code Playgroud)
我还希望断言成功(即传递构建)T={}.
Die*_*Epp 11
您可以使用模板专业化创建自己的支票.我已经扩大了检查范围以包括long double减少代码的大小.
#include <type_traits>
#include <vector>
template<class T>
struct is_ok {
static constexpr bool value =
std::is_floating_point<T>::value ||
std::is_integral<T>::value;
};
template<class T>
struct is_ok<std::vector<T>> {
static constexpr bool value =
std::is_floating_point<T>::value ||
std::is_integral<T>::value;
};
Run Code Online (Sandbox Code Playgroud)
这是一个演示:
#include <cstdio>
#define TEST(x) \
std::printf("%s: %s\n", #x, is_ok<x>::value ? "true" : "false")
int main() {
TEST(int);
TEST(float);
TEST(char *);
TEST(std::vector<int>);
TEST(std::vector<float>);
TEST(std::vector<char *>);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
int: true
float: true
char *: false
std::vector<int>: true
std::vector<float>: true
std::vector<char *>: false
Run Code Online (Sandbox Code Playgroud)
首先写一个测试一种类型的特征:
template<class T>
struct is_ok : std::is_arithmetic<T> { };
template<class T, class A>
struct is_ok<std::vector<T, A>> : std::is_arithmetic<T> { };
Run Code Online (Sandbox Code Playgroud)
然后测试该特征对于包中的每种类型都适用.我更喜欢使用@Columbo的bool_pack诀窍:
template<bool...> class bool_pack;
template<bool... b>
using all_true = std::is_same<bool_pack<true, b...>, bool_pack<b..., true>>;
template<class ...T>
void foo(T... t)
{
static_assert( all_true<is_ok<T>::value...>::value, "unsupported type!");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2354 次 |
| 最近记录: |