1

I want to do something like this...

class A;
class B;
class C;

void a(A);
void b(B);
void c(C);

template<typename T> void f(T t)
{
  if (some condition)
    a(t)
  else if (some other condition)
    b(t)
  else
    c(t);
}

int main()
{
    A myA;
    B myB;
    C myC;

    f(myA);  // some condition ensures f(myA) only calls a(myA)
    f(myB);  // some condition ensures f(myB) only calls b(myB)
    f(myC);  // some condition ensures f(myC) only calls c(myC)

    return 0;
}

But this doesn't compile because a(B), a(C), b(A), b(C), c(A), c(B) are not defined.

Is there a way to resolve this? I tried to see if std::function() or std::bind() could be used to construct a call to a(), b(), or c() dynamically, but no luck.

4

3 回答 3

6

不要使用模板。使用重载:

void f(A x) { if (some_condition)    a(x); }
void f(B x) { if (another_condition) b(x); }
void f(C x) { if (third_condition)   c(x); }

如果条件已在调用点确定,则将其从中删除,f并将对象保留在本地:

int main()
{
    if (some_condition)
    {
        A myA;
        f(myA);
    }
    else { /* ... */ }
}
于 2012-10-02T22:30:02.933 回答
4

您在寻找模板专业化吗?

template<typename T> void f(T t)
{
    // Generic implementation
}

// Specialization for A
template<> void f(A a)
{
    // A-specific behavior
}
// Repeat for B and C etc.
于 2012-10-02T22:30:37.823 回答
1

是的,重载函数(如上所述是要走的路)

但是,如果您必须进行分支并控制 a、b、c 的实现,则可以将 a()、b() 和 c() 声明为模板函数

template<class X>
void a(X aVar){ // impl of a(A); }
template<class X>
void b(X bVar){ // impl of b(B); }
template<class X>
void c(X cVar){ // impl of c(C); }
于 2012-10-02T22:32:58.433 回答