我在 Boost.hana 中使用 c++17 来编写一些元编程程序。困扰我的一个问题是在像 static_assert 这样的 constexpr 上下文中可以使用什么样的表达式。下面是一个例子:
#include <boost/hana.hpp>
using namespace boost::hana::literals;
template <typename T>
class X {
public:
T data;
constexpr explicit X(T x) : data(x) {}
constexpr T getData() {
return data;
}
};
int main() {
{ // test1
auto x1 = X(1_c);
static_assert(x1.data == 1_c);
static_assert(x1.getData() == 1_c);
}
{ //test2.1
auto x2 = X(boost::hana::make_tuple(1_c, 2_c));
static_assert(x2.data[0_c] == 1_c);
// static_assert(x2.getData()[0_c] == 1_c); // read of non-constexpr variable 'x2' is not allowed in a …Run Code Online (Sandbox Code Playgroud) 我正在使用 C++ lambdas 进行编程。出于性能原因,我想确保对 lambda 的调用由编译器内联。例如,我有这段简化的代码:
template <typename T>
auto gen_fn1(T x1, T x2) {
auto fn1 = [x1, x2]() {
return x1 + x2;
};
return fn1;
}
template <typename T>
auto gen_fn2(T x1, T x2) {
auto fn2 = [x1, x2]() {
auto fn1 = gen_fn1(x1, x2);
return fn1() * fn1();
};
return fn2;
}
int test_1() {
auto fn2 = gen_fn2(1, 2);
return fn2();
}
Run Code Online (Sandbox Code Playgroud)
我想确保 test_1() 中的 lambda 生成和调用不会引入额外的成本。我可以手动检查编译生成的汇编代码。通过 clang++8 的“-O2”优化,我可以看到预期的结果:在生成的代码中几乎只是“返回 9”。所以我的问题是:有没有办法自动检查我总能得到想要的结果?特别是,我想检查:
我有一个带有两个类型参数的 C++ 模板类 MyClass:
template <typename D, typename S>
struct MyClass {
private:
D d_;
S s_;
};
Run Code Online (Sandbox Code Playgroud)
我想添加一个以 D 和 S 引用作为参数的构造函数,这样它就可以推断出 D 和 S:
template <typename D, typename S>
struct MyClass {
// can bind to lvalues
constexpr MyClass(const D &d, const S &s): d_(d), s_(s) {}
// can bind to rvalues
constexpr MyClass(D &&d, S &&s): d_(std::move(d)), s_(std::move(s)) {}
private:
D d_;
S s_;
};
Run Code Online (Sandbox Code Playgroud)
效果很好。我可以从左值或右值创建对象:
auto c1 = MyClass(1, std::string("Hello")); // rvalues
auto idx = 2; …Run Code Online (Sandbox Code Playgroud)