我找到了一个不起眼的日志记录错误,事实上长度为2的初始化列表似乎是一个特例!这怎么可能?
代码是使用Apple LLVM版本5.1(clang-503.0.40)编译的CXXFLAGS=-std=c++11 -stdlib=libc++.
#include <stdio.h>
#include <string>
#include <vector>
using namespace std;
typedef vector<string> Strings;
void print(string const& s) {
printf(s.c_str());
printf("\n");
}
void print(Strings const& ss, string const& name) {
print("Test " + name);
print("Number of strings: " + to_string(ss.size()));
for (auto& s: ss) {
auto t = "length = " + to_string(s.size()) + ": " + s;
print(t);
}
print("\n");
}
void test() {
Strings a{{"hello"}}; print(a, "a");
Strings b{{"hello", "there"}}; print(b, "b");
Strings c{{"hello", …Run Code Online (Sandbox Code Playgroud) 假设我有一个这样的类:
class Foo
{
public:
Foo(int something) {}
};
Run Code Online (Sandbox Code Playgroud)
我使用以下语法创建它:
Foo f{10};
Run Code Online (Sandbox Code Playgroud)
然后我添加一个新的构造函数:
class Foo
{
public:
Foo(int something) {}
Foo(std::initializer_list<int>) {}
};
Run Code Online (Sandbox Code Playgroud)
施工会f怎样?我的理解是它将不再调用第一个构造函数,而是现在调用init list构造函数.如果是这样,这似乎很糟糕.为什么有这么多人建议在以后添加initializer_list构造函数时使用{}语法()来构造对象可能会默默地破坏事物?
我可以想象一个案例,我正在使用{}语法构造一个rvalue (以避免最烦恼的解析)但后来有人std::initializer_list为该对象添加了一个构造函数.现在代码中断,我不能再使用右值来构造它,因为我必须切换回()语法,这将导致最令人烦恼的解析.如何处理这种情况?
我想创建一个构造函数,它类似于int数组构造函数:int foo[3] = { 4, 5, 6 };
但我想像这样使用它:
MyClass<3> foo = { 4, 5, 6 };
Run Code Online (Sandbox Code Playgroud)
n我班上有一个私人大小的数组:
template<const int n=2>
class MyClass {
public:
// code...
private:
int numbers[n];
// code...
};
Run Code Online (Sandbox Code Playgroud) 我只是想知道是否有任何东西(在c ++ 11或boost中)可以帮助我做这样的事情:
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = {2, 5, 4};
std::list<int> res;
algorithm(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(res), std::plus<int>());
Run Code Online (Sandbox Code Playgroud)
结果当然应该是{3,7,7},而不是std :: plus可以是任何binary_function.
所以,如果有人有想法,请告诉我.
使用{}而不是()在构造函数中允许我在头文件中使用特定构造函数初始化类成员,如下所示:
class X {
private:
std::vector y{1, 2, 3};
};
Run Code Online (Sandbox Code Playgroud)
但是,我如何知道对于Z我使用的类Z z{a, b};将调用具有两个参数的构造函数Z::Z(int a, int b)- 而不是具有std::initializer_list?的那个?
我的意思是std::complex(1, 2)和std::complex{1, 2}是相同的,但std::vector(3)与std::vector{3}肯定不是.
除非我需要,我是否应该总是使用{}变体或使用?(){}
为什么用这两行代码打印出不同的结果?
std::cout << std::string{6, 's'}
std::cout << std::string(6, 's')
Run Code Online (Sandbox Code Playgroud)