Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模板类中的“using”是否强制实例化?_C++_Templates_Language Lawyer_Implicit Instantiation_Alias Declaration - Fatal编程技术网

C++ 模板类中的“using”是否强制实例化?

C++ 模板类中的“using”是否强制实例化?,c++,templates,language-lawyer,implicit-instantiation,alias-declaration,C++,Templates,Language Lawyer,Implicit Instantiation,Alias Declaration,这个问题是关于如何在运行main()之前使用全局变量初始化来实现一些副作用(例如,在main()之前注册工厂类)。当涉及模板时,这可能很棘手。考虑下面的代码: template <class T> class A { public: static bool flag; static bool do_something() { // Side effect: do something here. } template <boo

这个问题是关于如何在运行
main()
之前使用全局变量初始化来实现一些副作用(例如,在
main()
之前注册工厂类)。当涉及模板时,这可能很棘手。考虑下面的代码:

template <class T>
class A {
  public:
    static bool flag;
    static bool do_something() {
        // Side effect: do something here.
    }

    template <bool&>
    struct Dummy {};

    // Important: Do not delete.
    // This line forces the instantiation and initialization of `flag`.
    using DummyType = Dummy<flag>;
};

template <class T>
bool A<T>::flag = A<T>::do_something();

// A<int>::flag is instantiated and.
// A<int>::do_something will be called before main to initialize A<int>::flag.
class B : A<int> {};

我的问题是:<代码>使用< /Cord>技巧这里是编译器特定的东西,还是它被C++标准支持?我做了一些搜索,找到了一些关于标准14.7.1的信息,但仍然不确定关于
使用
的规则,因为它在14.7.1中没有提到(我的来源是,不确定它是否应该被视为基本事实)。另外,使用Dummy的
对我来说似乎有点黑客。有没有其他办法让它更优雅?目标是在代码< >类A/Ung>本身中解决实例化,从而使与副作用相关的代码段保持私有。< / P>当前C++标准是C++ 17。最终草案(仅在封面或页码等方面与最终版本不同)为。感谢提供信息。我看了一下,仍然没有找到任何关于使用
。您的源代码已有六年历史(2014年11月),甚至早于上一次发布的标准!在您的第一个示例中,clang和gcc调用了
do\u something
,但msvc没有。因此,至少在实践中,它是特定于编译器的。问题的关键在于[temp.inst]/3除非类模板或成员模板的成员已显式实例化或显式专门化,否则当在要求成员定义存在的上下文中引用专门化时,该成员的专门化将隐式实例化;特别是,静态数据成员的初始化(以及任何相关的副作用)不会发生,除非静态数据成员本身的使用方式要求静态数据成员的定义存在。
template <class T>
class A {
  public:
    static bool flag;
    static bool do_something() {
        // Side effect: do something here.
    }
  // The `using` dummy part is missing.
};

template <class T>
bool A<T>::flag = A<T>::do_something();

// A<int>::flag is not instantiated.
// A<int>::do_something will not be called.
class B : A<int> {};