c++ - 在编译时识别所有调用 function1<T> 的所有 T 然后添加行 function2<T>()

标签 c++ templates macros

是否有可能在任何地方识别某个函数的所有调用

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>()    

它会显着消耗 CPU(我分析过),因为 function1 每次都必须检查 function2 是否被调用。

最佳答案

这是一个近乎零开销的解决方案草案,只有在您要调用function1() 时才有效。之前main() :

#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;
}

输出(check it on IDEONE):

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

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

关于c++ - 在编译时识别所有调用 function1<T> 的所有 T 然后添加行 function2<T>(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37920850/

相关文章:

c++ - 函数模板修改用顶级 const 声明的参数 : clang bug?

C++ 将派生类作为基类模板参数传递

c - 带参数的宏

macros - 如何在另一个 crate 中使用一个宏?

c++ - WaitForMultipleObjects 在 64 位 Windows 上崩溃

c++ - cvFindContours 是如何工作的?

javascript - 当我用它来创建模板时,在tinymce中重新格式化代码

c++ - 为依赖类型特化 std::hash<T>

MACRO 可以定义为一个数组吗?

c++ - Visual Studio 不允许省略默认参数?