我想知道是否可以将模板函数(或其他)作为参数传递给第二个函数(不是模板).询问谷歌这个似乎只提供相反的信息(作为模板参数传递的函数)
我能找到的唯一相关页面是http://www.beta.microsoft.com/VisualStudio/feedbackdetail/view/947754/compiler-error-on-passing-template-function-as-an-argument-to-a-功能与省略号 (不是很有帮助)
我期待的是:
template<class N>void print(A input){cout << input;}
void execute(int input, template<class N>void func(N)){func(input)}
Run Code Online (Sandbox Code Playgroud)
然后打电话
execute(1,print);
Run Code Online (Sandbox Code Playgroud)
那么,这可以完成还是必须为execute()定义另一个模板?
我正在处理一个嵌入式项目(只有 C++14 编译器可用),我想优化执行速度。
这是我正在做的一个例子。
enum gpio_type{
TYPE_1,
TYPE_2
}
template <gpio_type T>
class test{
test(){}
void set_gpio(bool output)
{
switch (T)
{
case TYPE_1:
do_something();
break;
case TYPE_2:
do_something_else();
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译器会在编译时自动删除死代码吗?如果是,它是标准功能还是依赖于编译器?如果没有,是否有可能以强制优化的方式编写代码?
我最近偶然发现了将要引入C++ 17标准的std :: is_invocable,我想知道为什么它需要用户为函数指针提供一个类型,而不是只提供函数指针本身,这可能是更方便,特别是因为非类型模板参数现在可以不受约束.
我的意思可以在下面的例子中解释
void hello_world() {
cout << "Hello world" << endl;
}
int main() {
cout << std::is_invocable_v<decltype(hello_world)> << endl;
// as opposed to being able to do
// cout << std::is_invocable_v<hello_world> << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我不确定这是不是一个愚蠢的问题,所以如果它是拍我!
我经常遇到这种"困境".我在C++中说过两个重载函数
说我们有两个F的重载(下面只是一个伪代码)
void F(A a, .../*some other parameters*/)
{
//some code part
//loop Starts here
G1(a,.../* some other parameter*/)
//loop ends here
//some code part
}
void F(B b, .../*some other parameters*/)
{
//some code part
//loop Starts here
G2(b,.../* some other parameter*/)
//loop ends here
//some code part
}
Run Code Online (Sandbox Code Playgroud)
其中A和B是不同类型,G1和G2是做不同事物的不同功能.除了G1和G2线之外,重载的代码部分是相同的,并且它们有时非常长且广泛.现在问题是..如何更有效地编写代码.当然,我不想重复代码(即使它很容易做到这一点,因为它只是一个复制粘贴例程).一位朋友建议宏......但那看起来很脏.这很简单,因为如果我现在知道它是非常愚蠢的.将不胜感激任何建议/帮助.
编辑:对不起那些想要代码示例的人.这个问题实际上是抽象的,因为我遇到了不同的"相似"情况,我问自己如何使代码更短/更清洁.在大多数情况下代码很长,否则我不会在第一时间问这个问题.正如KilianDS指出的那样,确保函数本身不是很长也是很好的.但有时候这是不可避免的.在那里我遇到这样的许多情况下,循环嵌套甚至(在对方即几个循环)和年初˚F我们有一个循环的开始和结束˚F我们结束这种循环.
何塞
我写了一个说明问题的小例子.solve_bs1_y并solve_bs2_y实现完全相似.唯一的区别是函数调用:solve_bs*_z.不幸的是,似乎不可能将模板作为参数传递来替换函数调用solve_bs*_z.因此,我要实现每个solve_bs*_z另一个solve_bs*_y.有没有办法简化代码,以便我只需要一个实现solve_bs_y?
// Example program
#include <iostream>
#include <string>
template <int x, int y, int offs, class T>
float solve_bs1_z(T mat, float fS, float fT, float fU) {
return 1; // to keep it simple
}
template <int x, int y, int offs, class T>
float solve_bs2_z(T mat, float fS, float fT, float fU) {
return 2; // to keep it simple
}
// essentially the same …Run Code Online (Sandbox Code Playgroud) c++ ×5
templates ×3
c++14 ×1
c++17 ×1
loops ×1
macros ×1
non-type ×1
overloading ×1
performance ×1