如何检查,在参数组的参数有两种类型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={}.
假设我有 16 字节 ipv6 地址
\n\nstruct in6_addr {\n\xe3\x80\x80\xe3\x80\x80uint8_t s6_addr[16];\n};\nRun Code Online (Sandbox Code Playgroud)\n\n如何以跨平台方式将其转换为常规 IPv6 冒号分隔的字符串表示形式,并且无需访问 Internet?
\n\n我可以以某种方式在 char* 缓冲区中 sprintf 吗?
\n我的项目类似于此设置,当我需要使用my_template_library.h在main_class.h.
main.cpp中
#include "main_class.h"
int main()
{
MainClass m;
return m.exec();
}
Run Code Online (Sandbox Code Playgroud)
main_class.h
#ifndef MAIN_CLASS_H
#define MAIN_CLASS_H
#include "my_template_library.h"
class MainClass {
public:
MainClass();
int exec();
};
#endif // MAIN_CLASS_H
Run Code Online (Sandbox Code Playgroud)
main_class.cpp
#include <iostream>
#include "main_class.h"
MainClass::MainClass(){}
int MainClass::exec()
{
std::cout << "exec!" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
my_template_library.h
#ifndef MY_TEMPLATE_LIBRARY_H
#define MY_TEMPLATE_LIBRARY_H
#include <iostream>
//#pragma message ("I'm being included past the include guards!")
class MyTemplateLibrary
{
public:
MyTemplateLibrary();
void function();
};
MyTemplateLibrary::MyTemplateLibrary(){}
void MyTemplateLibrary::function()
{
std::cout …Run Code Online (Sandbox Code Playgroud) 我有
void foo(double &arg, uint8_t *data)
{
// ...
}
template <class T>
void foo(T &arg, uint8_t *data)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
我打电话给它
template <class ...T>
void bar(T... arg)
{
uint8_t *data = new uint8_t[SOME_VALUE];
// guaranteed to be executed in order
auto list = {(foo(arg, data), 1)...};
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是当使用0参数调用bar时它会失败,因为foo在初始化列表中调用了该方法.
如何修改它以bar使用空参数包?结果应该好像初始化列表从未执行过.
我想保持foo应用程序迭代,即使用初始化列表bar,而不是递归,当我们对fooin 进行单个调用时bar,variadic-template foo调用自身直到其参数包为空.(主要是因为后者看起来成本很高 - 当包有很多参数时,堆栈会掉落很多,并且会导致生成很多不同的模板版本foo.)