在编译时识别所有调用函数 1 的所有 T,<T>然后添加行函数 2<T>()

recognize all T of all calling function1<T> at compile time then add line function2<T>()

本文关键字:gt 函数 lt 然后 添加行 编译 调用 识别      更新时间:2023-10-16

是否有可能识别所有呼叫的所有呼叫everywhere every every

function1<T1>(); function1<T4>(); ...

然后添加一条线,该行在某个地方调用以下行?

function2<T1>(); function2<T4>(); ...

例如,

class X{
    template <class T> function1(){ }
    template <class T> function2(){ }
}
class A{}
class B{}
class C{}
int main(){
    X x;  
    //vvvv  this code (hopefully) will be auto generated (by macro?)
    x.function2<A>();
    x.function2<B>();    //<--- I don't care about order of A or B
    //x.function2<C>();  //<--- this line should not be generated
    //^^^^  Only X's function1 should be recognized,
    //             not other class's functions with the same name.
    x.function1<B>();  
    x.function1<A>();
    x.function1<B>(); ....  // called in various places in many .cpp
    //If it is called in another .cpp, but not here, it should still be recognized
}

编辑

我的旧代码调用: -

function2<T>() inside function1<T>()    

它的成本很大(我介绍了),因为函数1必须检查函数2是否每次都被调用。

这是一个接近零的开销解决方案的草稿,仅当您是不是之前,才能在main()之前调用function1()

#include <iostream>
#include <typeinfo>
template <class T>
void function2()
{
    std::cout << "function2<" << typeid(T).name() << ">()" << std::endl;
}
bool dummy = true;
template <class T>
struct Func1WasInstantiated
{
    struct CallFunc2
    {
        CallFunc2() { function2<T>(); }
        void operator()() const { dummy = false; }
    };
    static CallFunc2 callFunc2;
};
template <class T>
typename Func1WasInstantiated<T>::CallFunc2 Func1WasInstantiated<T>::callFunc2;
template <class T>
void function1()
{
    Func1WasInstantiated<T>::callFunc2();
    std::cout << "function1<" << typeid(T).name() << ">()" << std::endl;
}
int main()
{
    std::cout << "------- Entered main() ---------" << std::endl;
    function1<int>();
    function1<double>();
    function1<int>();
    return 0;
}

输出(在IDEONE上检查它):

function2<i>()
function2<d>()
------- Entered main() ---------
function1<i>()
function1<d>()
function1<i>()

全局变量dummy是副作用的受体,可确保将Func1WasInstantiated<T>::callFunc2链接到程序中,并使代码按预期工作。没有callFunc2()中包含的副作用,我可以想象一个积极优化的编译器,从function1()(正常)中消除该行,并让链接器将callFunc2对象删除,因为它们会变得未参考(我无法判断这是违反C 标准或不)。