小编Tho*_*mas的帖子

g ++,静态初始化和-nostdlib

编译/链接-nostdlib似乎可以防止静态初始化,即使我用.init/ .finisections 添加我自己的crti.s和crtn.s.

是否有解决方法使g ++生成插入的静态初始化代码.init或我可以手动调用?

这是我试过的:

g++ -o test.o -c -fno-use-cxa-atexit test.cc  # has _start (entry point) 
                                              #   that calls _init and _main
as -o crti.o crti.s      # has _init in section .init
as -o crtn.o crtn.s
g++ -o test ./crti.o test.o -nodefaultlibs -nostartfiles ./crtn.o
Run Code Online (Sandbox Code Playgroud)

-nodefaultlibs 单独包括静态初始化代码和调用,但强制使用libc-_start/_init.

-nodefaultlibs -nostartfiles 允许我使用自己的_start/_init,但不包括代码或调用静态初始化.

gcc g++ static-initialization

12
推荐指数
1
解决办法
1万
查看次数

在运行时选择正确的模板专业化

我有

template <int i> struct a { static void f (); };
Run Code Online (Sandbox Code Playgroud)

在代码中的不同位置完成专业化.如何仅在运行时调用正确a<i>::f的知识i

void f (int i) { a<i>::f (); } // won't compile
Run Code Online (Sandbox Code Playgroud)

我不想列出i一个大的所有可能的值switch.

编辑:

我想到了类似的东西

#include <iostream>

template <int i> struct a { static void f (); };

struct regf {
  typedef void (*F)();
  enum { arrsize = 10 };
  static F v[arrsize];
  template < int i > static int apply (F f) {
    static_assert (i < arrsize, "");
    v[i] …
Run Code Online (Sandbox Code Playgroud)

c++ templates template-specialization

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

成员变量和构造函数(取决于模板参数)

在C ++ 11中,仅当选择其默认模板值(当然,仅适用于int等受支持的类型)时,我才希望在类中具有一个成员变量,并为其初始化提供一个构造函数。

有什么推荐的方法可以做到这一点(允许增压)?

就像是:

template< int _x = -1 > struct C {
    C() {} // only available if _x != -1
    C( int x ) : x( x ) {} // only available if _x == -1
    // more methods that are common for all _x and refer to _x / x
    private:
    int x; // only available if _x == -1
    // more members that are common for all _x
};
Run Code Online (Sandbox Code Playgroud)

或者,换一种说法:对于大小和速度优化,如果选择了不同于模板默认值的另一个值,我想使用编译时间常数而不是存储在成员变量中的值。

-

这是使所有内容更清晰的示例:

template< int _size …
Run Code Online (Sandbox Code Playgroud)

c++ templates constructor member c++11

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

模板类的编译时计数器

想象一下,您有很多带有很多不同模板参数的类。每个类都有一个方法static void f()。您想将所有这些函数指针收集在列表 L 中。

运行时解决方案很简单:

typedef void (*p)();
std::vector<p> L;
int reg (p x) { static int i = 0; L.push_back(x); return i++; } // also returns an unique id

template <typename T> struct regt { static int id; };
template <typename T> int regt<T>::id = reg (T::f);

template < typename ... T > struct class1 : regt< class1<T...> > { static void f(); };
template < typename ... T > struct class2 : regt< class2<T...> > …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++11

4
推荐指数
1
解决办法
5573
查看次数

从任意数量的模板模板类继承

是否可以将任意数量的模板模板类传递给类?像这样的东西:

template < template < typename > ... class types > struct T {};
Run Code Online (Sandbox Code Playgroud)

完成后,我想继承他们,像这样:

template < typename p, template < typename > ... class types >
struct T : types <p> ... {};
Run Code Online (Sandbox Code Playgroud)

我怎么会得到那种行为?

c++ variadic-templates c++11

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