小编Swi*_*Pie的帖子

如何正确初始化模板类型的成员变量?

建议我有一个模板功能,如下所示:

template<class T>
void doSomething()
{
    T a; // a is correctly initialized if T is a class with a default constructor
    ...
};
Run Code Online (Sandbox Code Playgroud)

但是如果T是原始类型,则变量a未初始化.我可以写T a(0),但如果T是一个类,这不起作用.有没有办法在两种情况下初始化变量(T == class,T == int,char,bool,...)?

c++ templates

20
推荐指数
1
解决办法
2万
查看次数

GCC 中最早支持 __alignof__

我需要一种可移植的方法来确定结构的对齐要求,其中可移植性包括 GCC 的旧版本。部分项目受困于仅支持 C++11 之前标准的嵌入式平台,最早是 GCC v.3.6。

我可以使用一个非 ISO __alignof__(宏?函数?)的 C++11 运算符模拟alignof,但支持它的 GCC 编译器的最早版本是什么?命名方面是否有替代方案或更改?

c++ gcc memory-alignment

5
推荐指数
1
解决办法
467
查看次数

C++ 命名空间和 const 变量

我在 win10 中使用 Visual studio 2019 将这些文件编译为单个程序

我的项目只有两个源文件:

/**** a.cpp ****/

namespace pers{
    const int LEN = 5;
}
Run Code Online (Sandbox Code Playgroud)

/**** b.cpp ****/

namespace pers {
    const int LEN = 5;
}

int main() {
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

可以编译成功,但是不知道为什么?我定义了LEN两次!!

所以,我删除了const

/**** a.cpp ****/

namespace pers{
    int LEN = 5;
}
Run Code Online (Sandbox Code Playgroud)

/**** b.cpp ****/

namespace pers {
    int LEN = 5;
}

int main() {
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在不行了!所以,我的问题是发生了什么事?const不同源文件中的变量可以定义两次或多次(意味着不会出现多重定义错误)。

同时,如果这样做,编译器将抛出“多重定义错误”:

namespace pers {
    const int LEN …
Run Code Online (Sandbox Code Playgroud)

c++

4
推荐指数
1
解决办法
479
查看次数

模板推导:移植到C++ 11

以下代码对于C++ 14编译器是合法的

// g++ -std=c++14 -pedantic -pthread main.cpp
// output: 1 2 3 4 5 1 1 1 
#include <algorithm>
#include <vector>
#include <functional>
#include <iterator>
#include <iostream>

int main()
{
  std::vector<int> a = { 1, 2, 3, 2, 4, 5, 1, 1, 3, 5, 1, 5 }, b = { 2, 5, 5, 3 }, c;

  std::copy_if(a.begin(), a.end(), std::back_inserter(c), 
    std::bind(std::less<>(),   // this won't work in pre-C++14
      std::bind(
        std::count<std::vector<int>::iterator, int>, 
          std::bind(static_cast<std::vector<int>::iterator (std::vector<int>::*)()>(&std::vector<int>::begin), &c), 
          std::bind(static_cast<std::vector<int>::iterator (std::vector<int>::*)()>(&std::vector<int>::end), &c), 
          std::placeholders::_1
      ),
      std::bind(
        std::minus<>(), …
Run Code Online (Sandbox Code Playgroud)

c++ stdbind c++11 c++14

2
推荐指数
1
解决办法
116
查看次数

如何在参数包中找到最大值?

这是一个问题的示例:常量变量的模板应根据参数扩展其类型。尽管直接方法是可行的,但是通过提供类型的大小或基础类型名,它很容易出错。

#include <iostream>

template<size_t bit>
constexpr const uint16_t BIT = 1 << bit;

template<size_t... bits>
constexpr const uint16_t BITS = (uint16_t(1 << bits)|...);

int main()
{
    std::cout << BITS<0,1,3,12> << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

想法是实现模板数据类型,该数据类型将返回type为无符号整数,至少为参数包中最大值的大小。这也将允许检查模板参数是否合理。

c++ variadic-templates c++17

2
推荐指数
1
解决办法
190
查看次数