标准(§14.1)模板参数说:
允许模板模板参数的模板参数具有默认模板参数.
现在考虑以下代码:
#include <iostream>
using namespace std;
struct A {};
struct B {};
template<typename T = A>
struct X;
template<>
struct X<A> {
static void f() { cout << 1 << endl; }
};
template<>
struct X<B> {
static void f() { cout << 2 << endl; }
};
template< template<typename T = B> class C>
void g() {
C<>::f();
}
int main() {
g<X>();
}
Run Code Online (Sandbox Code Playgroud)
它的输出是:
出局:2
在这种情况下,模板模板参数是C.
但我不明白为什么 C<B>::f()被称为内部g().
考虑下面的代码,我不明白为什么必须定义print的空函数.
#include <iostream>
using namespace std;
void print()
{
}
template <typename T, typename... Types>
void print (const T& firstArg, const Types&... args)
{
cout << firstArg << endl; // print first argument
print(args...); // call print() for remaining arguments
}
int main()
{
int i=1;
int j=2;
char c = 'T';
print(i,"hello",j,i,c,"word");
}
Run Code Online (Sandbox Code Playgroud) 为什么g()首先调用函数?我定义g()为初始化列表中的第二个元素。
以下与初始值设定项列表相关的标准引用是否相关?
\n\n\n\n\n\xc2\xa78.5.4.4:在花括号初始化列表的初始值设定项列表中,\n 初始值设定项子句,包括任何由包扩展产生的\n (\xc2\xa714.5.3),在它们出现的顺序。
\n
#include <iostream>\n#include <vector>\n\nint f() { std::cout << "f"; return 0;}\nint g() { std::cout << "g"; return 0;}\n\nvoid h(std::vector<int> v) {}\n\nint main() {\n\n h({f(), g()});\n}\nRun Code Online (Sandbox Code Playgroud)\n\n输出:
\n\ngf\nRun Code Online (Sandbox Code Playgroud)\n 为什么A我初始化时没有调用默认构造函数std::vector?
std::vector<A> vec; //Doesn't call constructor
vec.push_back(A(2)); //Calls constructor
Run Code Online (Sandbox Code Playgroud)
我不明白这个,请问有人详细解释一下吗?