我正在处理一个嵌入式项目(只有 C++14 编译器可用),我想优化执行速度。
这是我正在做的一个例子。
enum gpio_type{
TYPE_1,
TYPE_2
}
template <gpio_type T>
class test{
test(){}
void set_gpio(bool output)
{
switch (T)
{
case TYPE_1:
do_something();
break;
case TYPE_2:
do_something_else();
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译器会在编译时自动删除死代码吗?如果是,它是标准功能还是依赖于编译器?如果没有,是否有可能以强制优化的方式编写代码?
考虑以下无法编译的代码:
#include <mutex>
#include <functional>
class t{
std::mutex m;
};
std::function<void(t test)> func = [](t test) {return;};
Run Code Online (Sandbox Code Playgroud)
生成以下错误:
错误:请求从“<lambda(t)>”转换为非标量类型“std::function<void(t)>”
你能向我解释为什么这种转换不起作用吗?
PS:现场示例:https : //godbolt.org/z/7se8crf41
在旧的 C 头文件中,我有以下映射(32 行):
#define IOCON_INDEX_PIO0_17 ( 0)
#define IOCON_INDEX_PIO0_13 ( 1)
#define IOCON_INDEX_PIO0_12 ( 2)
//...
Run Code Online (Sandbox Code Playgroud)
在 C++ 中,我可以有一个函数,它接受一个索引并返回一个 int。为此,我将仅在一行中初始化一个数组,但它的可读性不会很高。
我想用现代风格的 C++ 替换它。我曾想过使用这样的 lambda 表达式:
#include <array>
class test
{
int icon_index(int pio_index)
{
const std::array<int, 32> iocon_index = [](){
std::array<int, 32> buf;
buf[17] = 0;
buf[13] = 1;
buf[12] = 2;
//...
return buf;
}();
return iocon_index[pio_index];
}
};
Run Code Online (Sandbox Code Playgroud)
但是当我查看程序集生成的代码时,它似乎很大。我也想知道它将使用什么 RAM。
我必须使用符合 C++14 的编译器,所以:
constexpr
可能是答案的一部分... …
您将如何优雅地(以现代 C++ 方式)编写一个返回向量元素索引的函数,并将该向量作为参数,并引用其元素之一?
异常处理将不胜感激。
#include <vector>
template <class T>
std::size_t GetIndexFromRef(std::vector<T> &vec, T &item)
{
...
};
Run Code Online (Sandbox Code Playgroud) 我正在努力在编译时检查类型是否为 std::bitset 。
我想这样做:
is_bitset<std::bitset<2>>::value; // should evaluate to true
is_bitset<int>::value; // should evaluate to false
Run Code Online (Sandbox Code Playgroud)
我认为这篇SO 帖子指向了正确的方向,但由于某种原因,我无法使其与 std::bitset 一起使用。
用 C++14 做到这一点的最佳方法是什么?
我有一个枚举
enum ft_dev_type
{
SPI_I2C,
GPIO
};
Run Code Online (Sandbox Code Playgroud)
我希望能够构造这样的字符串
std::string s = "enum =" + SPI_I2C; //would contain "enum = SPI_I2C"
Run Code Online (Sandbox Code Playgroud)
为此,我试图重载 + 运算符
std::string operator+(const ft_dev_type type) const
{
switch (type)
{
case SPI_I2C: return std::string("SPI_I2C");
case GPIO: return std::string("GPIO");
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到
将 'ft_dev_type' 添加到字符串不会附加到字符串。
如何正确重载 + 运算符?
[编辑] 下面是类
class driver_FT4222
{
public:
driver_FT4222() {}
enum ft_dev_type
{
SPI_I2C,
GPIO
};
std::string operator+(const ft_dev_type type) const //this line is probably wrong
{
switch (type)
{
case SPI_I2C: return …
Run Code Online (Sandbox Code Playgroud)