签名模板类的C ++模板专业化

时间:2019-11-24 05:57:53

标签: c++ c++11 templates variadic-templates

我正在创建签名模板类。我遇到“ 无效”返回类型的问题。这是我处理无效返回类型的解决方案,这是我为其创建模板专门化类。

CAction< void(int a, int b, double c, std::string d)> on_action1;
on_action1.func(1, 2, 10.0, "a love b");

CAction< double(int a, int b, double c, std::string d)> on_action2;
on_action2.func(1, 2, 10.0, "a love b");

下面是我如何初始化类。

# importing shat is kinda annoying, not gonna lie
import turtle
import os
import time

# i dont even know what this section even means tbh
wn = turtle.Screen()
wn.title("BulletHeck")
wn.bgcolor("black")
wn.setup(width=800, height=800)
wn.tracer(0)

# i guess putting a score is almost always needed and now i cant think of a game that doesnt have score but im sure ive played a game that doesnt have it o wait now i remember its minecraft
score = 0


# random thing edit or whatever
marisa = turtle.Turtle()
marisa.speed(0)
marisa.shape("square")
marisa.color("white")
marisa.shapesize(stretch_wid=0.1,stretch_len=0.1)
marisa.penup()
marisa.goto(0, -100)

# pen or a pencil doesnt rly matter i guess
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 330)
pen.write("Score 0", align="center", font=("Comic Sans MS", 24, "normal"))

# this section doesnt rly make sense till u read the next one

def marisa_up():
    up = 1

    y = marisa.ycor()
    y += 10
    marisa.sety(y)

def marisa_down():
    y = marisa.ycor()
    y -= 10
    marisa.sety(y)

def marisa_right():
    x = marisa.xcor()
    x += 10
    marisa.setx(x)

def marisa_left():
    x = marisa.xcor()
    x -= 10
    marisa.setx(x)

# controls r needed i guess
wn.listen()
wn.onkeypress(marisa_up, "w")
wn.onkeypress(marisa_down, "s")
wn.onkeypress(marisa_right, "d")
wn.onkeypress(marisa_left, "a")


# yay we finnaly STARTED
while True:
    wn.update()

上面的代码正常工作。 我只是很好奇,除了上述方法,还有更好的解决方案吗?例如:我可以创建模板专用化成员函数( func )来处理“ void ”返回类型吗?如果您了解更多详细信息,请向我显示代码示例,非常感谢。

1 个答案:

答案 0 :(得分:1)

如果您有权使用C ++ 17,则可以抛出if constexpr并在每个分支中返回适当的值:

TRetType func(Args... a) {
  if constexpr(!std::is_void<TRetType>{}) {
      cout << "non void" << endl;
      TRetType nRet(0);
      return nRet;
    }
  else {
    cout << "void" << endl;
  }
}

否则,您可以使用标记分派技术根据返回类型进行重载。由于不能使用非模板功能来完成专业化工作:

template<class T>
struct type {};

TRetType func(type<TRetType>, long, Args... a) {
  cout << "non void" << endl;
  TRetType nRet(0);
  return nRet;
}

void func(type<void>, int, Args... a) {
  cout << "void" << endl;
}

TRetType func(Args... a) {
  return func(type<TRetType>{}, 0, a...);
}
相关问题