这个问题似乎与现有问题有关,但我不理解答案中提供的"便携式解决方法" (涉及const auto this_ = this;),而且我认为以下示例更容易理解.
我正在使用以下C++ 17代码片段(现场演示):
#include <iostream>
struct Test {
const char* name_{nullptr};
const Test* src_{nullptr};
constexpr Test(const char* name) noexcept
: name_{name}
{}
constexpr Test(const Test& src) noexcept
: src_{&src}
{
name_ = src_->name_;
src_ = nullptr;
}
};
template<char c>
void print_constexpr_char() {
std::cout << c << std::endl;
}
int main() {
constexpr const char* in = "x";
constexpr auto foo = Test{in};
constexpr auto bar = …Run Code Online (Sandbox Code Playgroud) 我试图找出为任意数量的维度编写通用容器(向量,矩阵,高维对象)的最佳方法.维度的数量以及每个维度的元素数量应在编译时指定,如下所示:
3 给出一个带有3个元素的向量10, 10 给出一个包含100个元素的矩阵7, 5, 3 给出具有105个元素的二阶张量一个人应该能够以简单的方式遍历所有元素进行简单的操作:double用标量乘以all()元素,在元素方面double添加两个兼容的容器等.另外,应该能够知道各自的索引遍历所有元素每个维度,例如从张(0, 0, 0)到(6, 4, 2)张量.
我认为可变参数模板参数是一个很好的工具,可以递归地连接每个维度的迭代器.
template<
int N, // the number of elements to iterate for this dimension
int... otherN // the other dimension's lengths
> class dimIterator;
Run Code Online (Sandbox Code Playgroud)
为了存储指向第一个元素的指针,我boxIterator记住了它只是dimIterators 的包装器
template<
typename dataType,
int... allN
> class boxIterator : public dimIterator<allN...> { // tried as member or inheritance
protected:
dataType* data;
public:
boxIterator(dataType* data) …Run Code Online (Sandbox Code Playgroud) GCC trunk(9.0)和Clang trunk(7.0)在以下代码上不一致:
template<int size_>
struct BadArray {
static constexpr int size = size_;// GCC complains due to this indirection
using Self = BadArray<size>;
Self& operator=(const Self&) noexcept = default;
};
Run Code Online (Sandbox Code Playgroud)
使用GCC进行编译失败,并显示错误消息
error: 'BadArray<size_>::Self& BadArray<size_>::operator=(const Self&)' cannot be defaulted
Run Code Online (Sandbox Code Playgroud)
而Clang接受代码(GCC 8.1和Clang 6.0的实例).
相关,但(IMHO)不同:类模板的嵌套模板参数推导不起作用
以下C ++ 17代码被GCC 8拒绝,但是clang对其进行编译没有任何问题。GCC的错误消息仅在有问题的行之前作为注释包含在内。
哪个编译器在这里正确?
template<class T>
struct Foo {
Foo(T) {}
};
template<class T>
struct Bar {
Bar(T) {};
};
void works() {
Bar bar{1};// {}
Foo foo(bar);// ()
}
void works_too() {
Foo foo{Bar{1}};// {{}}
}
void error_in_gcc() {
// error: 'auto' parameter not permitted in this context
Foo foo(Bar{1});// ({})
}
void but_this_works() {
Foo(Bar{1});// ({})
}
Run Code Online (Sandbox Code Playgroud) c++ ×4
c++11 ×2
c++17 ×2
clang++ ×1
constexpr ×1
g++ ×1
iterator ×1
optimization ×1
performance ×1
templates ×1