C ++函数模板的Decltype

时间:2016-03-11 02:48:28

标签: c++ templates

我想创建一个重载模板,如果一个类包含它,它会运行一个函数Foo(),否则它什么都不做。

class A
{
public:
    template <typename U>
    void Foo(U& u)
    {
        std::cout << "Has Foo()" << std::endl;
        // Modify u
    }
};

class B
{
    // Does not contain Foo()
};

我一直试图以此方式运行

template <typename T, typename U>
decltype(std::declval<T>().Foo()) TriggerFoo(T* t, U& u)
{
    t->Foo(u);
}
template <typename T, typename U>
void TriggerFoo(T* t, U& u)
{
    std::cout << "Does not have Foo()" << std::endl;
}

int main()
{
    A a;
    B b;
    U u;     // Some type

    TriggerFoo<A, U>(&a, u);    // I want to print "Has Foo()".
    TriggerFoo<B, U>(&b, u);    // Prints "Does not have Foo()".

    return 0;
}

目前,这两个课程都被传递给了#34;没有Foo()&#34;实例。它编译,但显然它不起作用,这很可能是因为我不能很好地理解declval。我也尝试过使用非模板函数,但它仍然不起作用。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

扩展Sam的答案,如果您不使用指针,则可以进一步简化代码,使代码看起来更整洁。

#include <iostream>
#include <type_traits>

class A
{
public:
    template <typename U>
    void Foo(U& u)
    {
        std::cout << "Has Foo()\n";
    }
};

class B
{
    // Does not contain Foo()
};

template <
  typename T,
  typename U,
  typename Z=decltype(std::declval<T>().Foo(std::declval<U&>()))>
void TriggerFoo(T& t, U& u)
{
    t.Foo(u);
}

template <typename... T>
void TriggerFoo(const T&...)
{
    std::cout << "Does not have Foo()\n";
}

class U {};

int main()
{
    A a;
    B b;
    U u;

    TriggerFoo<A, U>(a, u);    // I want to print "Has Foo()".
    TriggerFoo<B, U>(b, u);    // Prints "Does not have Foo()".

    return 0;
}

答案 1 :(得分:2)

您的方法存在两个基本问题:

decltype(std::declval<T>().Foo())

这永远不会成功解决,因为有问题的Foo()将始终采用参数。这部分应该是:

decltype(std::declval<T>().Foo(std::declval<U &>()))

但现在你会遇到另一个问题:当类实现Foo()时,模板解析将变得模糊不清。可以使用模板功能。

因此,您需要另一级别的间接和不同优先级的模板:

#include <iostream>
#include <type_traits>

class A
{
public:
    template <typename U>
    void Foo(U& u)
    {
        std::cout << "Has Foo()" << std::endl;
        // Modify u
    }
};

class B
{
    // Does not contain Foo()
};

template <typename T, typename U, typename Z=decltype(std::declval<T>().Foo(std::declval<U &>()))>
void DoTriggerFoo(T* t, U& u, int dummy)
{
    t->Foo(u);
}

template <typename T, typename U>
void DoTriggerFoo(T* t, U& u, ...)
{
    std::cout << "Does not have Foo()" << std::endl;
}

template <typename T, typename U>
void TriggerFoo(T *t, U &u)
{
    DoTriggerFoo(t, u, 0);
}

class U {};

int main()
{
    A a;
    B b;
    U u;     // Some type

    TriggerFoo<A, U>(&a, u);    // I want to print "Has Foo()".
    TriggerFoo<B, U>(&b, u);    // Prints "Does not have Foo()".

    return 0;
}

gcc 5.3的结果:

$ ./t
Has Foo()
Does not have Foo()

P.S:

std::declval<T &>().Foo(std::declval<U &>())

这可能会更好地与您的实际课程一起使用。