C++ 模板函数作为参数
我有这样的代码C++ 模板函数作为参数,c++,templates,C++,Templates,我有这样的代码 template<typename C> void invoke() { if (thing_known_at_runtime) { C::template run<int>(4); } else { C::template run<char>('a'); } } struct output { template<typename T> static void run(T x) { co
template<typename C>
void invoke() {
if (thing_known_at_runtime) {
C::template run<int>(4);
} else {
C::template run<char>('a');
}
}
struct output {
template<typename T>
static void run(T x) {
cout << x;
}
};
invoke<output>();
模板
void invoke(){
if(运行时已知的事物){
C::模板运行(4);
}否则{
C::模板运行('a');
}
}
结构输出{
模板
静态无效运行(T x){
cout你不能做这样的事情。在调用invoke
之前,你应该知道你想做什么。这样的事情会很好
void invoke(const std::function<void()>& func)
{
func();
}
template<typename T>
void output (const T& val)
{
std::cout << val << std::endl;
}
if (rand() % 2)
{
invoke(std::bind<void(&)(const int&)>(&output, globals::value_calculated));
}
else
{
invoke(std::bind<void(&)(const char&)>(&output, globals::value));
}
void调用(const std::function&func)
{
func();
}
模板
无效输出(常数T&val)
{
std::cout允许使用C++11吗?我是否正确理解您只想调用具有存储参数的函数?std::function如何帮助我?是的,允许使用C++11。我想调用具有存储(实际计算)参数的函数参数和模板参数。事实上,让我编辑这个示例来说明这一点。您不愿意定义两个版本的invoke()
?这不会顺利工作,因为函数只能通过函数指针传递,而函数指针在传递时需要一个具体的类型(即,您以后不能提供模板参数)。
void invoke(const std::function<void()>& func)
{
func();
}
template<typename T>
void output (const T& val)
{
std::cout << val << std::endl;
}
if (rand() % 2)
{
invoke(std::bind<void(&)(const int&)>(&output, globals::value_calculated));
}
else
{
invoke(std::bind<void(&)(const char&)>(&output, globals::value));
}