我想尝试将项目从gcc迁移到clang ++.我承认我的无知,我不知道为什么以下的代码
template <typename T>
constexpr T pi{std::acos(T(-1.0))};
Run Code Online (Sandbox Code Playgroud)
使用g ++静默编译但clang ++产生错误
trig.hpp:3:13: error: constexpr variable 'pi<float>' must be initialized by a constant expression
constexpr T pi{std::acos(T(-1.0))};
Run Code Online (Sandbox Code Playgroud)
而且我希望有人比我更了解它,可以启发我.
注意:尝试使用-std = C++ 14和C++ 1y.在clang版本3.6.2(标签/ RELEASE_362/final)下失败.适用于g ++(GCC)5.2.0.
TL; DR版本:
我正在设计一个C++ 14中的类是通用的.下面我描述一个设计问题,我将非常感谢能够实现我正在尝试的解决方案或重新设计的建议.
说我正在设计的课程被称为Algo.它的构造函数被传递unique_ptr给一个类型,比如说Business,它实现了一个接口(即,继承自纯虚拟类)并完成了大部分认真的工作.
我希望类型的对象Algo能够从Business它拥有的对象返回数据成员的指针(甚至是副本).但它无法知道Business想要返回的类型.我希望老板Algo知道根据Business他传入的内容会发生什么.
在我的C日里,我会通过传递void*并根据需要进行投射来吹掉类型系统.但是现在这种事情对我来说很糟糕.
更多详情:
因此,上述情况的一种伪C++ 14实现可能如下所示:
// perhaps a template here?
class AbstractBusiness {
. . .
public:
?unknownType? result();
};
class Algo {
//Could be public if needbe.
unique_ptr<AbstractBusiness> concreteBusiness_;
public:
Algo(std::unique_ptr<AbstractBusiness> concreteBusiness);
auto result() {return concreteBusiness_.result();}
};
class Business : public AbstractBusiness {
. . .
public:
std::valarray<float> data_;
std::valarray<float> result() {return data_;}
};
:::
auto b = …Run Code Online (Sandbox Code Playgroud) 在 C++17 中,是否有一种简单的方法来 std::visit 带有重载自由函数的变体,或者我必须使用带有重载调用运算符的对象?
换句话说,是否可以添加一些简单的东西来使以下//ERROR!行编译为与该//OK!行在功能上相同?
#include<variant>
#include<iostream>
#include<list>
#include <boost/hana/functional/overload.hpp>
using boost::hana::overload;
struct A {};
struct B {};
void foo(A) { std::cout << "Got an A!\n"; }
void foo(B) { std::cout << "Got a B!\n"; }
using AorB = std::variant<A,B>;
constexpr auto foo_obj = overload(
[](A){std::cout << "Got an A!\n";},
[](B){std::cout << "Got a B!\n";});
int main() {
std::list<AorB> list{A(), B(), A(), A(), B()};
for (auto& each : list) std::visit(foo, each); // ERROR!
for (auto& …Run Code Online (Sandbox Code Playgroud) 我似乎无法管理访问向量元素的语法,其指针包含在结构中.更多MWE之后:
#include <vector>
#include <stdio.h>
typedef struct vectag
{
std::vector<float> *X;
} vec;
int main ()
{
vec A;
A.X = new std::vector<float>(0);
A.X->push_back(5.0);
// This next line is the problem:
float C = A.X[0];
printf("%f\n", C);
return 1;
}
Run Code Online (Sandbox Code Playgroud)
GCC(G ++)说
14:24: error: cannot convert ‘std::vector<float>’ to ‘float’ in initialization
Run Code Online (Sandbox Code Playgroud)
当然,这是非常正确的.在该行中float C = A.X[0];,BX [0]将是正确的,如果X不是指针(召回std::vector<float> *X;).在operator []之前解除引用X的正确语法是什么,以便我可以访问X的元素?
PS我知道成员函数at(),它不是我的选项,因为我不想要范围检查的开销.这是性能关键代码的一部分.
c++ ×4
c++14 ×2
c++17 ×1
clang++ ×1
constexpr ×1
dereference ×1
polymorphism ×1
std-variant ×1
stdapply ×1
stdvector ×1