给出以下C++ 14代码:
struct A { /* heavy class, copyable and movable */ };
// complex code to create an A
A f(int);
A g(int);
A h(int);
const std::vector<A> v = { f(1), g(2), h(3) };
Run Code Online (Sandbox Code Playgroud)
我知道Ainitializer_list中的's被复制到向量中,而不是被移动(stackoverflow中有很多关于此的问题).
我的问题是:如何将它们移动到矢量中?
我只能做丑陋的IIFE(保持vconst)并且只是避免了initializer_list:
const std::vector<A> v = []()
{
std::vector<A> tmp;
tmp.reserve(3);
tmp.push_back( f(1) );
tmp.push_back( g(2) );
tmp.push_back( h(3) );
return tmp;
}();
Run Code Online (Sandbox Code Playgroud)
是否有可能使这优雅和高效?
PD:v 必须是std::vector<A>以后使用
以下简化示例编译gcc并且Visual Studio,但是失败了clang!?
namespace N
{
struct A {};
template <typename T>
double operator+ (T a, double d) {return d;}
template <typename T>
double operator+ (double d, T a) {return d;}
}
void test()
{
N::A a;
double x;
double y = a + x;
double z = x + a;
}
Run Code Online (Sandbox Code Playgroud)
在我看来,ADL可以找到模板operator+名称空间N.
为什么不clang同意?它是clang其他编译器中的错误吗?
这是来自clang 3.5.1的编译错误(在coliru上测试过),我不明白这里有什么问题......
10 : error: overloaded 'operator+' must have at least one parameter …Run Code Online (Sandbox Code Playgroud) c++ namespaces operator-overloading clang argument-dependent-lookup