小编Adi*_*dib的帖子

默认模板参数的范围是什么?

标准(§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().

c++ templates c++14

18
推荐指数
1
解决办法
417
查看次数

Variadic模板示例

考虑下面的代码,我不明白为什么必须定义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)

c++ c++11

11
推荐指数
3
解决办法
4943
查看次数

初始化列表中元素的求值顺序

为什么g()首先调用函数?我定义g()为初始化列表中的第二个元素。

\n\n

以下与初始值设定项列表相关的标准引用是否相关?

\n\n
\n

\xc2\xa78.5.4.4:在花括号初始化列表的初始值设定项列表中,\n 初始值设定项子句,包括任何由包扩展产生的\n (\xc2\xa714.5.3),在它们出现的顺序。

\n
\n\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}\n
Run Code Online (Sandbox Code Playgroud)\n\n

输出:

\n\n
gf\n
Run Code Online (Sandbox Code Playgroud)\n

c++ gcc operator-precedence

5
推荐指数
1
解决办法
1835
查看次数

为什么不初始化std :: vector <T>初始化T?

为什么A我初始化时没有调用默认构造函数std::vector

std::vector<A> vec; //Doesn't call constructor
vec.push_back(A(2)); //Calls constructor
Run Code Online (Sandbox Code Playgroud)

我不明白这个,请问有人详细解释一下吗?

c++ vector

-1
推荐指数
1
解决办法
124
查看次数

标签 统计

c++ ×4

c++11 ×1

c++14 ×1

gcc ×1

operator-precedence ×1

templates ×1

vector ×1