gpt4 book ai didi

c++ - 指针非类型模板参数的用途?

转载 作者:IT老高 更新时间:2023-10-28 22:26:22 33 4
gpt4 key购买 nike

有没有人使用过指针/引用/指向成员(非类型)模板参数?
我不知道应该将 C++ 功能用作最佳实践的任何(理智/真实世界)场景。

功能演示(用于指针):

template <int* Pointer> struct SomeStruct {};
int someGlobal = 5;
SomeStruct<&someGlobal> someStruct; // legal c++ code, what's the use?

任何启示将不胜感激!

最佳答案

指向函数的指针:

指向成员函数的指针和指向函数的非类型参数对某些委托(delegate)非常有用。它可以让你做出非常快速的委托(delegate)。

例如:

#include <iostream>
struct CallIntDelegate
{
virtual void operator()(int i) const = 0;
};

template<typename O, void (O::*func)(int)>
struct IntCaller : public CallIntDelegate
{
IntCaller(O* obj) : object(obj) {}
void operator()(int i) const
{
// This line can easily optimized by the compiler
// in object->func(i) (= normal function call, not pointer-to-member call)
// Pointer-to-member calls are slower than regular function calls
(object->*func)(i);
}
private:
O* object;
};

void set(const CallIntDelegate& setValue)
{
setValue(42);
}

class test
{
public:
void printAnswer(int i)
{
std::cout << "The answer is " << 2 * i << "\n";
}
};

int main()
{
test obj;
set(IntCaller<test,&test::printAnswer>(&obj));
}

Live example here .

指向数据的指针:

您可以使用此类非类型参数来扩展变量的可见性。

例如,如果您正在编写反射库(这可能对脚本非常有用),使用宏让用户为库声明他的类,您可能希望将所有数据存储在一个复杂的结构中(这可能随着时间的推移而改变),并且想要一些句柄来使用它。

例子:

#include <iostream>
#include <memory>

struct complex_struct
{
void (*doSmth)();
};

struct complex_struct_handle
{
// functions
virtual void doSmth() = 0;
};

template<complex_struct* S>
struct csh_imp : public complex_struct_handle
{
// implement function using S
void doSmth()
{
// Optimization: simple pointer-to-member call,
// instead of:
// retrieve pointer-to-member, then call it.
// And I think it can even be more optimized by the compiler.
S->doSmth();
}
};

class test
{
public:
/* This function is generated by some macros
The static variable is not made at class scope
because the initialization of static class variables
have to be done at namespace scope.

IE:
class blah
{
SOME_MACRO(params)
};
instead of:
class blah
{
SOME_MACRO1(params)
};
SOME_MACRO2(blah,other_params);

The pointer-to-data template parameter allows the variable
to be used outside of the function.
*/
std::auto_ptr<complex_struct_handle> getHandle() const
{
static complex_struct myStruct = { &test::print };
return std::auto_ptr<complex_struct_handle>(new csh_imp<&myStruct>());
}
static void print()
{
std::cout << "print 42!\n";
}
};

int main()
{
test obj;
obj.getHandle()->doSmth();
}

抱歉,auto_ptrshared_ptr 在 Codepad 和 Ideone 上均不可用。 Live example .

关于c++ - 指针非类型模板参数的用途?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13220502/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com